Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension - Trigger events on content_scripts using JQuery

I wrote a Chrome Extension that automatically fills some registration forms. There are some select fields that need to be triggered on "change" event in order to start some Ajax calls.

First I use JQuery attr or val to change the value of the select field, and than I use .trigger to invoke the "change" event, but this last one doesn't work.

Example:

I want to select the option that contains the word "London" and invoke the change element in order to start some operations of the native code that have some listeners on "change" event

jQuery("#SelectElement option:contains('London')").attr("selected", "selected"); 
jQuery("#SelectElement").trigger("change"); <--- not works

I tried also:

jQuery("#SelectElement option:containt('London')").attr("selected", "selected").change();

But if I try this code on console, it works.

Suggestions?

like image 671
user3817605 Avatar asked Aug 02 '14 11:08

user3817605


2 Answers

In my case,

var event = new CustomEvent('change');

did not work.

I had to initialize the event like this:

var evt = document.createEvent("HTMLEvents");
evt.initEvent("keyup", true, true);

First arg 'bubbles' should be true so the event should bubble up through the event chain.

event.initEvent(type, bubbles, cancelable);

Source: https://developer.mozilla.org/en-US/docs/Web/API/Event/initEvent

like image 25
ahebert Avatar answered Nov 19 '22 17:11

ahebert


I had the same problem and as far as I know it's because of something called framework event listeners. that you cannot trigger from your code by jquery! but the solution is trigger the event this way:

$(selector)[0].dispatchEvent(new Event("eventName"))

like image 110
mehdy Avatar answered Nov 19 '22 18:11

mehdy