【问题标题】:Chrome extension Content Script not loaded until page is refreshedChrome 扩展内容脚本在页面刷新之前未加载
【发布时间】:2014-01-18 21:01:11
【问题描述】:

我有一个 Chrome 扩展内容脚本,我想在 Trello 板上运行。目前,它仅包含:

console.log("Hello, world!");

当您通过内部链接打开 Trello 看板页面时,例如从我的看板页面,内容脚本不会运行。它会在您刷新页面后运行。

我的清单文件包含:

{
  "manifest_version": 2,

  "name": "Temp Ext",
  "version": "1.0",

  "content_scripts": [
    {
      "matches": ["*://trello.com/b/*"],
      "js":["contentscript.js"]
    }
  ]
}

谁能帮我弄清楚为什么最初加载页面时脚本没有运行?

编辑:更正的问题。问题仅在关注内部链接后出现,而不是任何链接。

【问题讨论】:

    标签: javascript google-chrome-extension trello


    【解决方案1】:

    问题在于 Trello uses HTML5's pushState 用于页面转换,因此内容脚本并不总是在打开板后运行。

    解决方案

    清单更改:

    {
      "manifest_version": 2,
    
      "name": "Temp Ext",
      "version": "1.1",
    
      "content_scripts": [{
        "matches": ["*://trello.com/*"],
        "js":["contentscript.js"]
      }],
    
      "background": {
        "scripts": ["background.js"]
      },
    
      "permissions": [
        "*://trello.com/*", "tabs", "webNavigation"
      ]
    }
    

    添加后台脚本:

    chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
        chrome.tabs.executeScript(null,{file:"contentscript.js"});
    });
    

    【讨论】:

    • 这对我很有用。 GitHub 做同样的事情。我唯一的区别是我必须更改 manifest.json 中的 "matches": 属性。以前我只为*://github.com/*/*.wiki 加载内容脚本。我在 out of github.com/* 页面的转换中捕捉到状态推送,但由于我没有加载 wiki 页面,我无法调用内容脚本。我将manifest.json 更改为"content_scripts": [ { "matches": ["*://github.com/*"], ...
    • finalllllllllly,一种真正有效的方法。你不知道我一直在寻找这样的东西多久。那里有这么多无用的“解决方案”
    • 也适用于我,但我需要它用于 Firefox。我将其更改为:browser.webNavigation.onHistoryStateUpdated.addListener(function(details) {browser.tabs.executeScript(null,{file:"contentscript.js"});});permissions 很重要。我忘记设置它们并得到一个未定义的错误。
    • 想要回应这个解决方案很棒。它在程序化和声明性内容脚本之间取得了很好的平衡。您可以为页面重新加载事件保留声明式注入的内容脚本,这很好,因为它们更易于调试。同时还处理推边案例!
    【解决方案2】:

    它非常适合我。我用你展示的两个文件创建了扩展:

    manifest.json:

    {
      "manifest_version": 2,
    
      "name": "Temp Ext",
      "version": "1.0",
    
      "content_scripts": [
        {
          "matches": ["*://trello.com/b/*"],
          "js":["contentscript.js"]
        }
      ]
    }
    

    contentscript.js:

    console.log("Hello, world!");
    

    然后我在此搜索线程中打开第三个链接:https://www.google.ca/search?q=trello+board+game&oq=trello+board+game&aqs=chrome..69i57.5037j0j1&sourceid=chrome&ie=UTF-8(“权力的游戏:棋盘游戏 - Trello”)和 Chrome DevTools 控制台写入“Hello,world!”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      相关资源
      最近更新 更多