defend orca
defend orca

Reputation: 743

Chrome extension click a button that is create by js

When I use contentscript click a button that make by Javascript on the website's page.

element.click()

I face the same problem: click is not a function, just like this:

Can't click a button using a Chrome extension, but I can in the developer tools

but, I can manual click the button to do something, just like download a file.

Thanks to the author, I got the solution:

var x =document.getElementById("someelement");
x.addEventListener('click',function myClick() {
  //here keep empty is ok. no need write anything
});
await sleep(10000);
x.click(); //this lead to the element 's original activity, just like download something....

Now, everything is ok, my question is: why? why this can solve the problem?

BTW, the question that I quote is not duplicate, because that is treat as duplicate, so I can not ask/answer this on the question directly.

Upvotes: 0

Views: 419

Answers (1)

CapitanFindus
CapitanFindus

Reputation: 1526

As content scripts works in an isolated context, your script .click is not aware of the list of handlers being fired by element.click() so it won't trigger anything. Adding a new handler from your content script will refer to the page's original script, and that's why it does trigger your event.

Anyway, this is a way to overcome the "isolation" stuff, another approach, which IMHO is more understandable, is to trigger a pure DOM Event

Something like this

const clickEvent = new Event('click');
const hasFired = element.dispatchEvent(clickEvent);
if(hasFired){
 // everything ok
} else {
 // someone blocked your handler
}

You could have a look to the Event reference as sometimes you could need to specify event options, try out this

const clickEvent = new Event('click', {cancelable: false, bubbles: true});

I remember I had the same issue as you and I solved it with this

Upvotes: 2

Related Questions