XrXr
XrXr

Reputation: 2057

Can't recieve port message from main.js in content script

I am trying to send a message via port from my main.js to my content script for my panel. I've tried many things without luck, however sending a message from the content script to main.js works perfectly.

Here is what my main.js looks like:

var data = require("self").data;
var setting = require("panel").Panel({
  width: 250,
  height: 130,
  contentURL: data.url("www.google.com"),
  contentScriptFile: data.url("script.js")
});
require("widget").Widget({
  id: "sorter1",
  label: "Search Result Sorting",
  contentURL: data.url("icon.ico"),
  panel: setting
});
setting.port.emit("message");

And here is my content script:

self.on("message", function(addonMessage) {
  document.innerHTML = "Got Message"
});

Upvotes: 1

Views: 655

Answers (2)

XrXr
XrXr

Reputation: 2057

I had this figured out a few days ago, just haven't had the time to post here.

A few things to keep in mind when using panels:

  • Pannel page is loaded when extension is loaded, not when it is shown.
  • Content script of the panel page is injected into the panel page when the page is shown.(when contentScriptWhen property is default)
  • Content scripts dont have access to add-on SDK resources.

This is how I implemented it

In main.js

panel.on("show", function() {
     panel.port.emit("message");
});

In panel content script

self.port.on("message", function() {
    //doThings
});

port.emit() doesn't need a second argument, though second argument is what will be passed to the content script for

function(secondArg) {
}

Upvotes: 1

therealjeffg
therealjeffg

Reputation: 5830

[Update] Sorry, I didn't fully read the code.

First off, you actually need to send the panel a message, eg

setting.port.emit('message', someData);

For the second part: I think you want:

self.port.on("message", function(addonMessage) {
    document.innerHTML = "Got Message"
});

The relevant docs are here:

https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/content-scripts/using-port.html

Upvotes: 0

Related Questions