1

Initially I posted this question. But subsequently I've got the answer by trial and error. Now I'd like to know the reason why my answer will work.

In the saved page below when I run $("#debitCard").change(); from extension it does not work but when I run from Chrome Console it works?

Why this behavior could be different from when run from Console? I've even run it within setTimeout

I've even created a button in the HTML upon clicking which it will call this function but even that isn't working. However calling from the Console is working every time.

Answer

I replaced this $("#debitCard").change(); to this:

var element = document.getElementById('debitCard');
var event = new Event('change');
element.dispatchEvent(event);

I want to know the reason of this quirk of Javascript/JQuery

enter image description here

Community
  • 1
  • 1
user5858
  • 1,082
  • 4
  • 39
  • 79

1 Answers1

5

The jQuery you have in the extension runs in a different scope to the jQuery or library in the content page.

If the functionality in the content page uses event handlers using jQuery or similar, you can't call those handlers from the jQuery in the extension scope because you cannot reference them.

But triggering the event, either natively or with jquery in the content script, does work and will fire the page's handlers.

Edit:

This issue has been in my head since this post and today I found an example that illustrates my original point - that you can't (always) fire event handlers using jQuery:

The target:

<a id="vcemail-link"  href="#" onclick="signOut();">Sign out...</a>

I cannot trigger this onclick event using jquery from my extension, I have to use the native version

$('#vcemail-link').click(); // doesn't work
document.getElementById('vcemail-link').click(); // works

This may or may not satisfy you @user5858 but it's significant and worth remembering, I presume it will apply to inline onchange() also.

the reference

Troy Wray
  • 938
  • 5
  • 15
  • just added the reference. It explains from the horse's mouth. – Troy Wray Nov 27 '17 at 05:16
  • I just spent ages trying to find a public page I could try this on, thinking I would prove my answer. I didn't, I disproved (part of) it. I'm modifying my answer as it has some value but it *isn't an answer to your question*. You can't call the event handlers directly (obvious huh?) because you can't reference them. But if they are event driven, you can trigger those events natively or with jquery in the extension scope. – Troy Wray Dec 03 '17 at 07:10
  • What I did was to inject javascript intro the page and managed to be able to trigger events that way. – aifrim Dec 05 '17 at 17:13