2
votes

I'm learning firefox addon development using the new AddOn SDK. I'm creating a simple utility addon which autohides the comments on SPOJ Problems Page.
Now, to hide comments section, there's a option on problem page which calls a javascript function to do so. Currently I temporarily achieved the functionality by simulating a click on this option, but it uses unsafewindow which is not recommended.

Here's the main.js

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

tabs.on('ready', function(tab) {
    var worker = tab.attach({
            contentScriptFile : data.url("autoHide.js")
    });

    worker.port.emit('hideComments', tabs.activeTab.url);
});  

And autoHide.js

self.port.on('hideComments', function(url) {
    var elem = document.getElementById('comments_sh');
    //toggleComments();
    elem = elem.parentNode;
    simulateClick(elem);

});

function simulateClick(a) {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, unsafeWindow,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  a.dispatchEvent(evt);      
}

The function which I want to call is toggleComments().

So my question is How can I call a javascript function of WebPage through Addon Script or ContentScript ??

2
You can inject a script to the page adding the event listener - juvian

2 Answers

1
votes

Your generic question at the end has been asked several times, but I think there's an easier solution in this circumstance.

What happens if you replace simulateClick with

function simulateClick(a) {
  a.dispatchEvent(new CustomEvent('click'));      
}

?

If that doesn't work, then you'll have to edit to page's js code to add a custom event listener that will run the same function that is run on click then dispatch that custom event from the add-on's content script, as described in the answer to the first question I linked to.

1
votes

Since a simple non-navigation click would work for you, HTMLElement.click() should be sufficient:

self.port.on('hideComments', function(url) {
    var elem = document.getElementById('comments_sh');
    elem.parentNode.click();
});

General reference about interacting with page scripts.