jQuery $(document).off() 在 Chrome 扩展中不工作

jQuery $(document).off() not working in Chrome extension

我已经创建了一个 Chrome 基于 https://thoughtbot.com/blog/how-to-make-a-chrome-extension 的扩展(查看最后的完整文件)

我做了两个更改:我使用 jQuery 3.1.1 最小化而不是上面页面中给出的旧版本,我更改了 content.js:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if( request.message === "clicked_browser_action" ) {
            $(document).off("touchmove mousewheel mousemove scroll");
        }
    }
);

当我在打开相应测试页面的情况下单击扩展按钮时,$(document).off() 命令不起作用。它不会报错,只是什么都不做。

我查过了。如果我在我想要影响的页面上的控制台中输入 $(document).off("touchmove mousewheel mousemove scroll");,它就可以正常工作。如果 运行 在扩展名中则不是。

我尝试检查扩展中的 document 是否正确,并且 document.domain 在扩展中的断点(以及页面上的控制台)中检查时给出了正确的结果。

我尝试检查 jQuery._data( jQuery(document)[0]).events["touchmove"](和 "mousewheel"、"mousemove"、"scroll")并且它在控制台中有效,但我收到错误消息(Cannot read property 'touchmove' of undefined) 如果我断点扩展。当我进一步检查时,jQuery._data( jQuery(document)[0]) 给出以下内容:

在控制台中:

Object
    events: Object
    handle: function (e)
    __proto__: Object

在断点中:

Object
    __proto__: Object

我已经尝试了一些其他的东西(例如,jQuery 可以访问和工作,等等)。

您正在尝试执行 $(document).off() 以删除 jQuery 由页面脚本(网页中已存在的脚本;即不是您的内容脚本)添加的事件处理程序。 jQuery 存储哪些事件处理程序已添加到正在使用的 jQuery 实例内部的数据结构中。您的内容脚本与页面脚本的 context/scope 不同。因此,当您在内容脚本的上下文中执行 $(document).off() 时,该 jQuery 实例不知道页面脚本添加的任何偶数处理程序并且无法删除它们。

要使您的 $(document).off() 有效,它必须在页面脚本上下文中 运行。在页面脚本上下文中执行代码的最常见方法是创建 <script> 元素并将其插入页面的 DOM.

您可以将代码更改为:

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);
        }
    }
);

添加的脚本在页面上下文中获得 运行,因为它现在是 DOM 中的 <script> 元素。浏览器识别出添加了 <script> 元素,并在插入它的脚本不再处理时对其进行评估(执行包含的代码)。对于您添加到 DOM 的任何其他元素,它的作用基本相同。因为它是页面的一部分,<script> 中的代码在页面脚本 context/scope.

中得到 运行

虽然上述方法有效,尤其是对于如此短的代码,但我创建 <script> 元素以在页面上下文中执行代码的首选方法是使用我编写的名为 executeInPage() 的函数。您可以在 .

中找到该函数