0

I have a Chrome Extension that, in a content script, listens for specific events on the page it is injected into.

The listeners are created on a focusin event - because the elements I want to listen for only exist in certain situations.

Everything works great...except every time the user focusins (understandably) new listeners are created. So I end up with many duplicate events.

My Extension works with very specific pages, so I know whether they have Jquery or not...this one does.

In the focusin listener I have:

 $('.PageClass_I_listen_for').blur(function(){
  console.log('blurred out of comment area...');
  //Do something
 });

I've tried including 'off' commands at the start of the focusin listener - to kill any existing event listeners before adding a new one. The following code does not have any effect:

$(document).off('click', '.PageClass_I_listen_for');  //  Kill events

Perhaps you cannot kill events (understandably) that are part of a page into which your code is injected?

Any way to get around this?

Help appreciated!

11teenth
  • 1,853
  • 1
  • 15
  • 28
  • You're not using `off` correctly, you've added a `blur` event listener and you're trying to remove a `click` event listener. Here is the [DOCUMENTATION for `jQuery.off`](http://api.jquery.com/off/) – Titus Aug 06 '18 at 16:38
  • This is an extension-specific task. Since the content script runs in *isolated world* you need to run the `off` code [in page context](https://stackoverflow.com/a/9517879) to use jQuery of the page, as opposed to jQuery of your content script. – wOxxOm Aug 06 '18 at 16:44
  • @wOxxOm, thank you! – 11teenth Aug 06 '18 at 17:13

1 Answers1

0

Rather than attach event listeners directly to elements, I strongly you use event delegation.

Basically, you attach a single event listener somewhere in the hierarchy above the element you're interested in. Then, it doesn't matter if elements are added or removed dynamically later on.

$(document).on( 'blur', '.PageClass_I_listen_for', function( e ) {
  // use e.currentTarget here
} );

Your code for .off doesn't work because you are not removing from the same elements you are adding the events to, nor are you removing the same type of event. You added the event directly to the elements, but you removing events delegated to document.

See: https://learn.jquery.com/events/event-delegation/

error
  • 694
  • 4
  • 14
  • 1
    Thank you for the comments and help...I just didn't connect using a document-level even listener in a Chrome content page. Total mind block and lack of understanding the basic mental model for me...but this did the trick and the nightmare appears to be over...:) – 11teenth Aug 06 '18 at 17:12