【问题标题】:Chrome Extension doesn't inject content script after redirectChrome 扩展程序在重定向后不注入内容脚本
【发布时间】:2020-08-19 11:07:41
【问题描述】:

我正在开发一个与 Twitter 交互并在用户访问 twitter.com/home 时注入内容脚本的 Chrome 扩展程序。我在 manifest.json 中声明了 content_scripts,并且在 twitter.com/home 上一切正常。但是,当我访问 twitter.com 时,它会重定向到 twitter.com/home,并且扩展程序不会注入内容脚本。将“twitter.com”添加到 manifest.json 中的“matches”列表可以解决问题,但我希望扩展仅在 twitter.com/home 加载时注入脚本。我正在考虑使用 webNavigation API 来检测重定向,但我想知道是否有更有效的方法来实现这一点。谢谢!

manifest.json

  "name": "xxx",
  "version": "1.0",
  "description": "abc",
  "permissions": [
    "activeTab",
    "declarativeContent",
    "storage"
  ],
  "content_scripts": [
    {
      "matches": ["https://twitter.com/home", "https://twitter.com/"],
      "run_at": "document_idle",
      "js": ["script.js"]
    }
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "manifest_version": 2
}

【问题讨论】:

标签: google-chrome-extension


【解决方案1】:

Twitter 正在通过 ajax 加载页面,而不是页面重新加载。因此,当您单击页面上的项目时,页面内容发生了变化,URL 也发生了变化。但页面实际上并没有重新加载,这就是你的内容脚本不起作用的原因。

这样做: 将您的 matches 更改为 https://twitter.com/*。这将使内容脚本注入到所有 twitter 页面。

在您的内容脚本script.js 中,您需要添加一些逻辑来检测用户是否在home 页面上。 由于页面没有重新加载,您需要使用MutationObserver 之类的东西来检测页面内容的变化(比如home 链接是否突出显示)。以便您的脚本知道当前页面是home 页面并执行您想做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2012-06-15
    • 2017-04-07
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多