Chrome Extension - Trigger events on content_scripts using JQuery

♀尐吖头ヾ 提交于 2020-05-12 20:00:27

问题


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?


回答1:


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"))




回答2:


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



来源:https://stackoverflow.com/questions/25094387/chrome-extension-trigger-events-on-content-scripts-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!