javascript - 注入(inject)脚本时出错

标签 javascript google-chrome-extension

我正在尝试开发一个 Chrome 扩展程序,以便在单击按钮时打开一个新选项卡,然后在其中执行 js。

list :

{
  "author": "...",
  "name": "...",
  "manifest_version": 2,
  "version": "1.0",
  "description": "...",
  "background": {},
  "browser_action": {
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs","http://*/","https://*/"
  ]
}

popup.html:

<html>
<head>
  <script src="jquery.min.js"></script>
</head>
<body>
  <button type="button" id="saveBtn">Save</button>
  <script type="text/javascript" src="popup.js"></script>
</body>
</html>

popup.js:

$("#saveBtn").click(function(){
  chrome.tabs.create({
    selected:false, 
    url:'https://analytics.google.com/something...'
  },function(tab){
    chrome.tabs.executeScript(tab.ib,{file:"jquery.min.js"});
    chrome.tabs.executeScript(tab.ib,{file:"html2canvas.js"});
    chrome.tabs.executeScript(tab.ib,{file:"FileSaver.js"});
    chrome.tabs.executeScript(tab.id,{file:'inject.js'});
  });
});

所有 javascript 文件都位于同一文件夹中。我收到此错误

Unchecked runtime.lastError while running tabs.executeScript: Cannot access a chrome:// URL at Object.callback (chrome-extension://jamfjopkccgnbpkhafanifhjambepphc/popup.js:8:23)

在我尝试注入(inject) jquery.min.js、html2canvas.js 和 FileSaver.js 但不是注入(inject).js 的行上!新选项卡正确打开,回调被执行,但随后抛出错误。我在这里做错了什么?

最佳答案

你那里有错别字。

chrome.tabs.executeScript(tab.ib,{file:"jquery.min.js"});
chrome.tabs.executeScript(tab.ib,{file:"html2canvas.js"});
chrome.tabs.executeScript(tab.ib,{file:"FileSaver.js"});
chrome.tabs.executeScript(tab.id,{file:'inject.js'});

前三个具有 tab.ib 而不是 tab.id,它将传递 undefined。在这种情况下,Chrome 将尝试在当前选项卡中运行脚本,该选项卡可能是 chrome://extensions 或类似的内容。

来自文档:

integer (optional) tabId
The ID of the tab in which to run the script; defaults to the active tab of the current window.

顺便说一下,您可能想看看this question确保您的脚本以正确的顺序执行。

关于javascript - 注入(inject)脚本时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37001843/

相关文章:

google-chrome - Chrome 扩展程序可以访问本地存储吗?

javascript - Chrome 内容脚本制作一个 cookie;当 chrome 重新启动时,cookie 将被删除。如何让它稳定?

javascript - Chrome 扩展 NativeMessaging 'connectNative' 未定义

javascript - Chrome 扩展 : Add content (enable/disable icon)

google-chrome - Google Chrome 开发者工具中的 Step 和 Step Into 有什么区别?

javascript - 加载资源失败 : the server responded with a status of 404 (Not Found) in React. js 项目已部署

javascript - 无法覆盖函数的内部变量

javascript - 如何从 angularjs 中的表中向上/向下移动突出显示的选定行?

ES6 中的 Javascript 类,如何将它们导入到其他 js 文件和 html 文件中?

javascript - 多个可拖动图表 d3.js