Webextension Content script return Promise to page-script

Hi!
The case is as follow.

  1. Content script creates object and clone it to window to be accessible from page script code.
  2. Cloned content script object has a method which is asynchronous call and I want to return Promise to page script.
    Xray vision prevent returning object to page script.
    The only way I found to inform page script from content script about state of async method is Window.postMessage.
    Are there any other solution to implement in more elegant way to using Promise style in calling content script object from page script code?
    Here is sample code which is disallowed from Xray vision to return promise .
// content script
var jsPrintSetup = {
  print: function(printSettings) {
    return new Promise(
      function (resolve, reject) {
        // calling async print ...
        if (some_condition)
          resolve(res);
        else
          reject(err);
      }
    );
  }
}

window.wrappedJSObject.jsPrintSetup = cloneInto(
  jsPrintSetup,
  window,
  {cloneFunctions: true}  
);

// page script
window.jsPrintSetup.print(null).then(
  (res) => {
    // ok resolved
  }
  , (err) => {
    // rejected
  } 
);

Try

return new window.wrappedJSObject.Promise(...)

You may have to use exportFunction or something on the argument to Promise. Also, make sure you are aware of all the security implications of what you are doing.

I have tried with window.wrappedJSObect bet get an error Error: Permission denied to access object.
exportFunction is not applicable to Permission object.

// content script
//...
    return new window.wrappedJSObject.Promise(
      function (resolve, reject) {
        // calling async print ...
        if (some_condition)
          resolve(res);
        else
          reject(err);
      }
    );
  }
//...

What I meant was:

return new window.wrappedJSObject.Promise(exportFunction((resolve, reject) => /*...*/))

That might just avoid the Error: Permission denied to access object.


I have no idea what you mean.

I’ve was in mistake.
The above is work as I needed.
Finally i’ve tested this code and is working.

Thank you!

// content script
var jsPrintSetup = {
  print: function(printSettings) {
    return new window.wrappedJSObject.Promise(
      exportFunction(
        function (resolve, reject) {
          // calling async print ...
          if (some_condition)
            resolve(res);
          else
            reject(err);
        }
        , window.wrappedJSObject
     )
    );
  }
}

Reviving this issue in 2022.

While returning a promise appears to work, the then() method on the promise cannot be called due to permission being denied.

The inability for promises to cross the cloneInto/exportFunction boundary has been raised here: https://bugzilla.mozilla.org/show_bug.cgi?id=1757066