2

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 ??

1
  • You can inject a script to the page adding the event listener Commented Jun 23, 2014 at 18:41

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, this worked. However I'm more interested in knowing how to communicate to page script and elements through addon script. Any reference or resource will be helpful.
@willma Since this came up more than once, I now created a wiki-answer: stackoverflow.com/questions/24378116/…
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.