MDN self-hosted library · e01.org
cloneInto() / notebook

cloneInto()

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
const clonedObject = cloneInto(myObject, targetWindow);
js
targetWindow.foo = clonedObject;
js
// content script
const addonScriptObject = { greeting: "hello from your extension" };
window.addonScriptObject = cloneInto(addonScriptObject, window);
js
// page script
button.addEventListener("click", () => {
  console.log(window.addonScriptObject.greeting); // "hello from your extension"
});
js
// Content script
window.foo.addonScriptObject = cloneInto(addonScriptObject, window);
js
// page script
function foo(greeting) {
  console.log(`they said: ${greeting.message}`);
}
js
// content script
const addonScriptObject = { message: "hello from your extension" };
window.foo(cloneInto(addonScriptObject, window)); // "they said: hello from your extension"
js
// content script
const addonScriptObject = {
  greetMe() {
    alert("hello from your extension");
  },
};
window.addonScriptObject = cloneInto(addonScriptObject, window, {
  cloneFunctions: true,
});
js
// page script
const test = document.getElementById("test");
test.addEventListener("click", () => {
  window.addonScriptObject.greetMe();
});
js
// content script
const addonScriptObject = {
  body: window.document.body,
};
window.addonScriptObject = cloneInto(addonScriptObject, window, {
  wrapReflectors: true,
});
js
// page script
const test = document.getElementById("test");
test.addEventListener("click", () => {
  console.log(window.addonScriptObject.body.innerHTML);
});