【发布时间】:2020-08-02 23:51:39
【问题描述】:
在我的扩展程序中,我正在创建一个选项卡并从名为 background.js 的后台脚本中打开一个名为 results.html 的 html 文件。创建选项卡后,我将一个名为 results.js 的 javascript 文件注入到新创建的选项卡中。
但它会在我的background.js 控制台中引发以下错误:
Unchecked runtime.lastError: Cannot access contents of url "chrome-extension://hcffonddipongohnggcbmlmfkeaepfcm/results.html".
Extension manifest must request permission to access this host.
浏览其他 stackoverflow 问题的解决方案,我尝试在 manifest.json 中添加以下权限:
<all_urls>-
chrome-extension://*抛出错误:权限“chrome-extension://*”未知或 URL 模式格式错误。
但以上都不起作用。
此外,注入后的results.js 应该向background.js 发送消息,以响应一些数据以馈入results.html。
我的代码:
manifest.json
{
"manifest_version":2,
"name":"Extension Name",
"description":"This is description of extension.",
"version":"1.0.0",
"icons":{"128":"icon_128.png"},
"browser_action":{
"default_icon":"icon.png",
"default_popup":"popup.html"
},
"permissions":["activeTab", "background", "tabs", "http://*/*", "https://*/*","<all_urls>"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"web_accessible_resources": ["addAlias.js","results.html","results.js"]
}
background.js
/*Some code*/
function loadResult()
{
chrome.tabs.query({active:true},function(tabs){
//creating tab and loading results.html in it
chrome.tabs.create({url : 'results.html'}, function(tab){
//injecting results.js file in the tab
chrome.tabs.executeScript(tab.id, {file: 'results.js'});
});
});
}
/*somecode*/
if(/*some condtion*/)
{
loadResult(); //calling function
}
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse)
{
//Listening for results.js request for data
if( request.greeting === "sendResults")
{
console.log(" Results request received .");
//sending data back to results.js
sendResponse({failed:failedToAdd,succeed:succeedToAdd});
}
}
results.js
/*Some code*/
console.log("I got loaded");
console.log("Now requesting for sendResults");
//Below sending request for data
chrome.runtime.sendMessage({greeting: "sendResults"},
function (response) {
console.log('Got data from Background.js');
/*Some Code*/
}
);
【问题讨论】:
-
executeScript 仅用于在网页中运行内容脚本,您不能在此处使用它。见Pass data or modify extension html in a new tab/window
-
@wOxxOm 感谢从第 4 种方法中获得灵感,我将 results.js 添加到 results.html 并从 results.js 发起消息
-
@wOxxOm 能否请您在此处写下答案,以便我接受它作为解决方案。
-
如果您从工作解决方案中发布片段可能更有意义。
标签: javascript google-chrome google-chrome-extension