gvidik
gvidik

Reputation: 21

worker.port.on doesn't get events

main.js complete code:

const data = require("self").data;
const pageMod = require("page-mod");
pageMod.PageMod({
  include: "*",
  contentScriptFile: data.url("addButtons.js"),
  onAttach: function(worker) {
        worker.port.on("testEvent", function(name) {
            window.alert(name);
        });
     }
});

addButtons.js, extract:

<...>
var img=document.createElement("img");
img.setAttribute('src', '...');                  
     img.onclick=function() { 
            var name='printMe';
            self.port.emit("testEvent", name);
        //  window.alert(name);
        }
<...>

The goal is to send event from addButton.js to main.js by clicking to img and show alert with argument. If I uncomment line //window.alert(name); in addButton.js - I'll get the alert, i.e. onclick function works fine. But described above code doesn't show me alert or any errors in console. I have read all concerning documentation but it didn't help.

Upvotes: 2

Views: 170

Answers (1)

Wladimir Palant
Wladimir Palant

Reputation: 57691

The event is sent fine - it's simply that there is no window and consequently no window.alert() in your extension (if you open Error Console by pressing Ctrl-Shift-J you should see this error). You can only use window.alert() in content scripts because they are attached to a web page, in extension modules you should use console.log() instead.

Upvotes: 1

Related Questions