0
votes

Using Addon SDK I am trying to inject script to page on every page load. To test things, plugin is trying to add variable to window object and page should read it. When I run this, I can see "injecting" alert, but page gives me error "undefined property window.myVar". What am I doing wrong? Btw I don't want to use unsafeWindow.

main.js:

var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");

pageMod.PageMod({
    include: "*",
    contentScriptFile: data.url("inject.js"),
    contentScriptWhen: "start",
    onAttach: function(worker) {
        worker.port.emit("inject", "unused param");
    }
});

inject.js

function inject(arg) {
    var script = document.createElement("script");
    script.innerHTML = 'alert("injecting"); window.myVar=54564;';
    document.head.appendChild(script);
}
self.port.on("inject", inject);

page.html

<html>
  <head>
  </head>
  <body>
    <script>
      alert(window.myVar);
    </script>
  </body>
</html>

EDIT: I tried canuckistani's code and it shows some weird behavior. Btw I am on Firefox 31. Here is my code

function inject(arg) {
    var myVar = 123;
    unsafeWindow.myVar = cloneInto(myVar, unsafeWindow);
}
self.port.on("inject", inject);

and page

<html>
  <head>
  </head>
  <body>
    <script>
      alert(window.myVar); <!--This shows empty alert box-->
      alert(window.myVar); <!--This shows alert box with right value (123)-->
    </script>
  </body>
</html>
1
The only way to access the page's window object is through unsafeWindow. This topic has been covered a million times, most exhaustively here. - willlma
My guess is a slight timing error in when the content script is injected. I would recommend slightly delaying access to the global - attaching the content script takes time. - therealjeffg

1 Answers

0
votes

Starting with Firefox 30 ( almost 2 versions ago! ) you can use some new apis to do this. This would look like:

let myVar = {1:2};

self.port.on("inject", function() {
    unsafeWindow.myVar = cloneInto(myVar, unsafeWindow);
});

For more information, see this blog post: