Reputation: 6749
I have an event on a page that I need to fire from a Chrome Extension. I do not have access to modify the page's JavaScript.
$(selector).live("click", fn);
I need to trigger this with native JS in my Chrome extension, like this:
selectorElement.click(); //doesn't work
Of course that above won't work because the live
function is being used. How can I trigger it though?
Thanks!
Upvotes: 0
Views: 754
Reputation: 115950
If you don't have jQuery, you can fire DOM events using dispatchEvent
:
var selector = "#...";
var elmList = document.querySelectorAll(selector);
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elm[0].dispatchEvent(evt);
This code fires on the first element matching the selector, but it could be modified to loop over elmList
if you needed to fire on several elements at once.
Upvotes: 4