I'm writing a Firefox addon using the SDK and I'm having trouble trigger click events on elements within a page.
I'm using the SDK page-mod module as well as jQuery. Stripped down to the scope of this issue, I have the following:
/* main.js */
var self = require("sdk/self");
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "http://example.com/*",
contentScriptWhen: "ready",
contentScriptFile: [
self.data.url("jquery.js"),
self.data.url("myScript.js"),
]
});
/* myScript.js */
$(document).on('click', '#target', function() {
var buttons = $('button'); // get all buttons on the page
if(buttons.length) {
buttons.each(function() {
$(this).trigger('click');
});
}
});
The problem is when I click the #trigger
element on the page, the JS executes fine until it gets to the following line:
$(this).trigger('click');
Then the following error is thrown:
Permission denied to access property 'length'
jquery-2.1.1.js:4330
So it seems that the addon is not able to send a click event from itself to the page. Any ideas how to solve this?
Edit: for reference here is a small block of the relevant code in the jQuery source:
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data ); // line 4330
if ( event.result === false ) {
event.preventDefault();
}
}
The best solution is always to replace jQuery with pure JavaScript (which executes faster too), here is how you can rewrite myScript.js
to do so:
document.getElementById("target").addEventListener('click', function() {
var buttons = document.getElementsByTagName("button"); // get all buttons on the page
if(buttons.length) {
for (var i = buttons.length - 1; i >= 0; i--) {
buttons[i].click();
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.