0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
defend orca
  • 617
  • 7
  • 17

1 Answers1

2

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

CapitanFindus
  • 1,498
  • 15
  • 26
  • before my solution, I had try this, unfortunately, It is not work as expect. until now only my function can call the origin function successfully. origin function means that function define by the website page themself that not define by my content script. – defend orca May 01 '20 at 23:51
  • @保卫逆戟鲸defendorca try out with the updated answer, with options. I had your same issue and I solved it that way – CapitanFindus May 02 '20 at 11:28
  • yes, actually we use almost same solution. and you have a stable concept with it:) thank you. – defend orca May 05 '20 at 04:38