我正在尝试开发一个 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/