Selecting <option> of a <select> from a chrome extension content script

╄→尐↘猪︶ㄣ 提交于 2019-12-03 08:04:36

I dont really know JQuery, but here's how to do it without JQuery and without injecting anything into the page....

var selections = document.querySelector('#woot');

selections.value = 17;

var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", true, true);
selections.dispatchEvent(evt);

You can append a script. It'll take a lot of script appends but you can always put a custom communication event, and only inject one good script listening to that custom event and eval()ing the event data. It will work if there's no CSP.

var RunInThisContext = function(c){ try{
    var code = document.createTextNode(c);
    var script = document.createElement('script');
    script.type='text/javascript';
    script.language='javascript';
    script.appendChild(code);
    try{document.body.appendChild(script);}catch(e){document.head.appendChild(script);}

}catch(e){ console.error('ERROR: '+e); }}; 

Use like this:

RunInThisContext('('+(function(){ 
     $('select').change();
}).toString()+'()); '); 

But bear in mind you're running this directly into the page. If page doesn't have jQuery you'll have to include it first.

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