问题
I am building a Firefox add-on using the addon-sdk.
The add-on has one button that displays a panel on click. The panel has a content script running it. Now, I need the panel to look different depending on the user's current tab and occasionally show an external url.
So, the main.js script tracks the current tab of the user and sends messages to the content script using panel.port.emit() and the content script changes the HTML of the panel to match whatever is needed.
However, as I mentioned, some times the panel is just showing an external url, so I need to reset it back to its original url. This is my code:
function panelListMode(currentTab, data){
panel.resize(350,300);
//This is the line causing the trouble
panel.contentURL = self.data.url("panel.html");
console.log("sending message");
panel.port.emit("generateList",data);
}
If I emit the message after changing the contentURL the content script does not seem to receive a thing. I now that specific line is the one causing the problem because if I comment it the content script receives the message.
Something tells me this is because the panel needs to load the DOM again and I need to wait until it is ready before the content script is able to do anything. But... aren't content scripts something apart from just included scripts?
As far as I am able to tell the panel has no "ready" event of sorts that I can listen to for emitting the message.
What am I missing?
Edit: After some experimentation I have been able to find some more. If I copy panel.html to the same directory as panel2.html and change my function so it goes:
function panelListMode(currentTab, data){
panel.resize(350,300);
//This is the line causing the trouble
panel.contentURL = self.data.url("panel2.html");
console.log("sending message");
panel.port.emit("generateList",data);
}
The problem is gone. I have experimented a bit and it seems that when I try to change the contentURL to the html that is already set in the panel the content script stops working all together.
This is some really odd behavior... have I encountered a bug?
回答1:
As far as I am able to tell the panel has no "ready" event of sorts that I can listen to for emitting the message.
I think it does, at least internally it seems to but I'm not sure whether they're exposed.
But even if it doesn't you can simply fire your own port message from the content script once it has been attached and registered its own listeners. Upon receiving that message in the addon you can then resume using the port on that side.
来源:https://stackoverflow.com/questions/28953220/why-is-my-add-on-panel%c2%b4s-content-script-no-longer-responding-to-port-messages-af