【问题标题】:Chrome Extension: chrome.tabs.executeScript not workingChrome 扩展:chrome.tabs.executeScript 不起作用
【发布时间】:2014-10-25 17:52:27
【问题描述】:

我正在编写一个 chrome 扩展程序,并且想从我的后台脚本中执行一个内容脚本。后台脚本执行,但内容不执行。以下是相关的代码块:

manifest.json:

"background": {
    "scripts": ["js/app/background.js"],
    "persistent": true
},

"permissions": [
    "identity",
    "tabs",
    "activeTab",
    "*://*/*"
]

background.js:

console.log('background')
chrome.tabs.executeScript(null, {file: "content.js"})

content.js

console.log('content')

当我检查元素时,控制台登录了background,但没有登录content。常规控制台也没有任何记录。我做错了什么?

【问题讨论】:

  • 你必须签入标签的控制台,而不是后台页面的控制台。
  • 那里也没有任何显示。
  • 为什么不设置tabId?应该在哪个选项卡内容脚本中执行?

标签: javascript google-chrome google-chrome-extension content-script


【解决方案1】:

在您的 background.js 中,将您的 chrome.tabs.executeScript 包裹在此:

chrome.tabs.onUpdated.addListener(function(tab) {

    chrome.tabs.executeScript({
        file: '/scripts/runsOnPageLoad.js'
    }); 

});

【讨论】:

    【解决方案2】:

    我无法让程序化注入工作,所以我刚刚在 manifest.json (https://developer.chrome.com/extensions/content_scripts#registration) 的 content_scripts 字段中指定了它

    【讨论】:

    • 这确实是声明内容脚本的正确方法,这些脚本应该在与某个 URL 匹配的所有页面上运行。
    【解决方案3】:

    您应该添加权限“activeTab”。更多信息https://developer.chrome.com/extensions/content_scripts#pi

    【讨论】:

      【解决方案4】:

      必须如下所述:

      chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
      chrome.tabs.executeScript({
              code:"alert('Any Javascript code comes here !');"
          });
      

      });

      注意:可以在后台脚本执行,不要忘记在 manifest.json 中允许必要的权限

      【讨论】:

        猜你喜欢
        • 2017-04-20
        • 2013-12-24
        • 2017-05-26
        • 2012-01-22
        • 2012-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多