【问题标题】:Getting ""Uncaught TypeError: Could not add listener" When Using " chrome.webNavigation.onCompleted.addListener"使用“chrome.webNavigation.onCompleted.addListener”时获取“”Uncaught TypeError:无法添加侦听器“
【发布时间】:2019-03-28 17:51:30
【问题描述】:

当尝试使用 Chrome 的 WebNavigation.onCompleted 在某个 url 上运行 background.js 时,我收到错误 “未捕获的 TypeError:无法添加侦听器”。 对于 manifest.json 中的权限,我已授予对 activetab 和 webrequest 的扩展访问权限。

我尝试过使用其他监听器,例如 chrome.browserAction.onClicked.addListener 它工作得很好。我也在使用最新版本的 chrome (v73)。

背景.js:

 chrome.webNavigation.onCompleted.addListener(function(tab) {
    var eurl = tab.url.split("/skill/");
    if(eurl[0] === "https://www.duolingo.com") {
        chrome.tabs.executeScript(tab.ib, {
            file: 'jquery-3.3.1.min.js'
        });
        chrome.tabs.executeScript(tab.ib, {
            file: 'duohelperinjector.js'
        });}

}, {url: [{urlMatches : '*://duolingo.com/skill/*'}]});

manifest.json:

{
    "name": "DuoHelper",
    "version": "0.0.1",
    "manifest_version": 2,
    "description": "A Chrome Extension That Helps With Duolingo",
    "homepage_url": "https://github.com/TechHax/DuoHelper",
    "background": {
      "scripts": [
        "background.js"
      ],
      "persistent": true
    },
    "browser_action": {
      "default_title": "DuoHelper"
    },
    "permissions": [
      "webNavigation",
      "activeTab"
    ]
  }

我得到的错误:

未捕获的类型错误:无法添加侦听器

如果扩展程序正常工作,我希望 chrome 扩展程序在其 url 为 *://duolingo.com/skill/* 的活动选项卡上注入 javascript 文件。

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    查看documentationurlMatchesRE2 regular expression,而不是URL match pattern

    解决方案 1。

    正确的 RE2 表达式是 'https?://(www\\.)?duolingo\\.com/skill/.*'

    解决方案 2。

    更好的方法是对主机名和路径进行纯字符串比较,因为它比使用正则表达式要快得多,并且文档明确建议仅在绝对不可避免时才使用正则表达式:

    chrome.webNavigation.onCompleted.addListener(info => {
      chrome.tabs.executeScript(info.tabId, {file: 'jquery-3.3.1.min.js'});
      chrome.tabs.executeScript(info.tabId, {file: 'duohelperinjector.js'});
    }, {
      url: [{
        hostSuffix: '.duolingo.com',
        pathPrefix: '/skill/',
      }],
    });
    

    请注意 hostSuffix 如何利用 API 在第一个组件之前添加的隐式点来匹配 duolingo.com 的任何子域。另外,回调参数不是tab,而是一个different object,里面有tabId

    解决方案 3。

    使用declarativeContent API,如文档中所示,但不是 ShowPageAction 而是指定 RequestContentScript,尽管文档中的警告实际上在稳定的 Chrome 中有效。

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 2021-04-09
      • 2011-08-16
      • 2023-01-19
      • 1970-01-01
      • 2019-06-24
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多