Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

javascript - Triggering a click event from content script - chrome extension

In my chrome extension's content script, I click on certain links/buttons on webpages from certain sites. To do that, I use following code in the content script (I embed jQuery in the content script):

$(css_selector).trigger("click")

This works on most sites.

However, on certain sites like delta.com, match.com, and paypal.com, this way of triggering a click on elements does not work. On delta.com, I get following exception thrown when I attempt triggering in the content script:

Error: An attempt was made to reference a Node in a context where it does not exist.
Error: NotFoundError: DOM Exception 8

Strange thing is, if I open javascript consoleon delta.com, include a jQuery and attempt the same click triggering code snippet, it works.

On match.com and paypal.com, triggering simply does not work in the content script and there is no error. I cannot even trigger "click" event through javascript console the way I did on delta.com.

If I manually use mouse click, everything works fine on all the three sites. Hence I also tried to simulate that using mousedown(), mouseup(), but that did not work either.

This seems to be issue because javascripts from those sites are hijacking and ignoring events. I tried to read code from these sites to see what is happening but there was simply too much code.

Does anyone have any idea about what is happening here and how to fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Due to browser extension sand-boxing, and basic jQuery functionality, you cannot trigger a non-jQuery click event with trigger or click.

You can however call the raw DOM element click method, which will act exactly as if the element was clicked with the mouse. Just use [0] to access the DOM element:

$(css_selector)[0].click();

Although you would seldom need to, you can trigger all matching buttons using the same code in an each. As the this in an each is the DOM element it is quite simple:

$(css_selector).each(function(){
    this.click();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...