Skip to content

Commit

Permalink
promise cloneinto clarification (mdn#19125)
Browse files Browse the repository at this point in the history
* promise cloneinto clarification

* corrections

* Created separate promise cloning section
  • Loading branch information
rebloor committed Aug 12, 2022
1 parent cf40380 commit 7be5afe
Showing 1 changed file with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ In Firefox, part of the isolation between content scripts and page scripts is im

The purpose of this feature is to make it harder for the less-privileged script to confuse the more-privileged script by redefining the native properties of objects.

So for example, when a content script accesses the page's [window](/en-US/docs/Web/API/Window), it won't see any properties the page script added to the window, and if the page script has redefined any existing properties of the window, the content script will see the original version.
So, for example, when a content script accesses the page's [window](/en-US/docs/Web/API/Window), it won't see any properties the page script added to the window, and if the page script has redefined any existing properties of the window, the content script will see the original version.

## Accessing page script objects from content scripts

Expand Down Expand Up @@ -188,7 +188,7 @@ window.wrappedJSObject.messenger = cloneInto(
{cloneFunctions: true});
```

Now page scripts will see a new property on the window, `messenger`, which has a function `notify()`:
Now page scripts see a new property on the window, `messenger`, which has a function `notify()`:

```js
window.messenger.notify("Message from the page script!");
Expand Down Expand Up @@ -261,3 +261,19 @@ window.eval(`

document.dispatchEvent(ev); // true, undefined, "unwrapped", "propC"
```

### Promise cloning

A Promise cannot be cloned directly using `cloneInto`, as Promise is not supported by the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). However, the desired result can be achieved using `window.Promise` instead of `Promise`, and then cloning the resolution value like this:

```js
let promise = new window.Promise(resolve => {
// if just a primitive, then cloneInto is not needed:
// resolve("string is a primitive");

// if not a primitive, such as an object, then the value must be cloned
let result = { exampleKey: "exampleValue" };
resolve(cloneInto(result, window));
});
// now the promise can be passed to the web page
```

0 comments on commit 7be5afe

Please sign in to comment.