Skip to content Skip to sidebar Skip to footer

Jquery $(document).off() Not Working In Chrome Extension

I've created a Chrome Extension based on https://thoughtbot.com/blog/how-to-make-a-chrome-extension (look at the end for the completed files) I've made two changes: I used jQuery 3

Solution 1:

You're attempting to execute $(document).off() in order to remove jQuery event handlers that were added by page scripts (scripts that already exist in the webpage; i.e. not your content script). jQuery stores which event handlers have been added in data structures internal to the jQuery instance being used. Your content script is in a different context/scope from that of page scripts. Thus, when you execute $(document).off() in the context of your content script, that jQuery instance isn't aware of any of the even handlers which have been added by the page scripts and can't remove them.

For your $(document).off() to be effective, it must be run in the page script context. The most common way to have code execute in the page script context is to create and insert a <script> element to the page's DOM.

You could change your code to:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if( request.message === "clicked_browser_action" ) {
            let newScript = document.createElement('script');
            newScript.innerHTML='$(document).off("touchmove mousewheel mousemove scroll");';
            document.head.appendChild(newScript);
        }
    }
);

The added script gets run in the page context because it's now a <script> element in the DOM. The browser recognizes that a <script> element was added and evaluates it (executes the code contained) as soon as the script which inserted it is no longer processing. It does basically the same thing for any other element you add to the DOM. Because it is part of the page, the code inside the <script> gets run in the page script context/scope.

While the above works, particularly for such short code, my preferred method of creating <script> elements to execute code in the page context is to use a function I wrote called executeInPage(). You can find that function in my answer to "Calling webpage JavaScript methods from browser extension".

Post a Comment for "Jquery $(document).off() Not Working In Chrome Extension"