1

I am writing a chrome extension that accesses the active tab page and manipulates the DOM by injecting some code with a content script. However, I am having no luck when it comes to firing event handlers that should be registered by the active tab page's own JavaScript.

For example, on the web page itself there is a save button that saves all the form data when clicked. On my chrome extension, I have a button that, when clicked, sends a message to a content script. The content script then has a line of code to fire the web page save button's event handler to save the form data, but it does not work, even when I tell it to do so using $('#btnSave').click().

Another example, I have a button on my chrome extension that when clicked, selects a value from the drop down list located on the web page. It selects the value fine, but it does not fire the change event for the drop down list, even when I explicitly tell it to do so using $('#ddl').change().

Both commands fire the respective controls events fine when I type them in the console, but not when using them in my content script. So how do I access the web page's event handlers from my content script?

P.S. Have also tried invoking event handler using .trigger(event), .triggerHandler(event), .change() for select, and my code is wrapped inside $(document).ready().

wizloc
  • 2,202
  • 4
  • 28
  • 54

1 Answers1

1

Setting a value programatically does not fire the change event. Just like calling click() does not necessarily call all the handlers. You have to manually fire it. I would suggest you use the function at this answer since it's not jQuery specific.

Note that if you use the function mentioned, you can fire a click event and it will behave just as if a user clicked something. However, for the change event, you have to make the change programatically and then fire the change event

// Trigger a user click and the event
fireEvent($('#btnSave')[0], 'click');

// Make a change and fire a change event
var ddl =  $('#ddl');
ddl.val('something');
fireEvent(ddl[0], 'change')
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • Would you be able to explain why going to the console and typing in .change() fires the change event, but does not do so when ran in my code? – wizloc Feb 11 '16 at 16:06
  • My best guess is that calling `$().change` only fires events registered with jQuery – Ruan Mendes Feb 11 '16 at 16:35
  • @wisloc That would be [this](http://stackoverflow.com/questions/27913065/gmail-chrome-extension-chrome-extension-undefined/27913209) since you're by default executing in the page's context. – Xan Feb 12 '16 at 00:47