0

I need to pass my variable defined in my content script to the script that I inject into the web page. For example, I need to use an image defined in the content script like this:

var myImage = browser.extension.getURL("myImage.jpg");

Then I inject some script from the content script to the loaded page as:

var s = document.createElement('script');
s.src = browser.extension.getURL("myscript.js");
document.body.appendChild(s);

How can I access the variable "myImage" in the script "myscript.js"?

1 Answers1

0

you can use either CustomEvent or window.postMessage and in myscript.js listen to the event or message.

Example for window.postmessage

window.postMessage({type: 'image-var', params: myImage }, "*");

in myscript.js

 window.addEventListener('message', function (e) {
        if (e.data.type === 'image-var') {
            console.log(e.data.params);
        }
    });

Example for CustomEvent:

document.dispatchEvent(new CustomEvent('yourCustomEvent', { detail: data }));

in myscript.js

document.addEventListener('yourCustomEvent', function (e) {
  var data = e.detail;
  console.log('received', data);
});
Hemant
  • 129
  • 1
  • 6