I’m using a context-menu item click to show a dialog (using JQuery/Bootstrap) that lets users submit the text they selected to a web service via AJAX (this all works perfectly). Once submitted, I intend to display an Add-on SDK notification to say ‘Thanks for your submission’.
Now, I know I need to send a message from the content script to the Add-on script to show the notification, but my message doesn’t arrive when sent from a callback function.
My add-on code (extract):
var pageMod = require("page-mod");
pageMod.PageMod({
include: ['*'],
contentScriptWhen: "end",
contentScriptFile: [ data.url("js/content.js") ],
onAttach: function onAttach( worker, mod) {
worker.port.on("submittedNotif", function(msg) {
console.log('Hello');
notifications.notify({ ... });
})
}
});
Content-script follows. I’ve indicated the situations where the message arrived, and where it doesn’t.
// Handle the context-menu Item's click and show the dialog
self.on("click", function(node,data) {
self.port.emit("submittedNotif", '*** DOES NOT ARRIVE ***');
showDialog( 'DialogName', function (response) { /* Do stuff */ });
})
self.port.emit("submittedNotif", '*** Arrives OK ***');
function showDialog( str, response) {
// Dialog stuff
self.port.emit("submittedNotif", '*** DOES NOT ARRIVE ***');
}
I’m told self is a global object, so I shouldn’t have to pass it as a parameter, surely. It’s just not clear to me how trying to send via self.port.emit should work differently depending on where it’s used within the content script. I’m not aware of any threading issue, for example. Perhaps this is a gap in my JavaScript knowledge, but can anyone tell me what I’m doing wrong?
I solved my own problem. Here’s how, and what I learned.
Firstly, the content-script, and the
context-menuItem’s click handler:Now, the old
self.port.emitgot me nowhere, but switching toself.postMessageand adding anonMessage()to thecontext-menuItem finally gives me the event I want.I now also pass
selfto theshowDialog()method [which goes against what I was told aboutselfbeing global…?!], as the parameter ‘eventHandler’:Again, I drop the
self.port.emit, switching toself.postMessage, and calling that on the handler that was passed-in.And finally, the
notifications.notify({ ... });call gets moved from thePageMod‘sonAttach()to the menu Item’sonMessage(). In short, everything that happens in response to that click now happens within the scope of the menu item.All works now. Perhaps this all seems obvious in retrospect – but the documentation definitely confused rather than clarified, especially the difference between
portandpostMessage()