Abh*_*hay 7 javascript google-chrome google-chrome-extension
在我的扩展中,我创建一个选项卡,并results.html从名为 的后台脚本打开一个在其中命名的 html 文件background.js。创建选项卡后,我将注入一个名为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.
Run Code Online (Sandbox Code Playgroud)
浏览其他 stackoverflow 问题的解决方案时,我尝试在以下位置添加以下权限manifest.json:
<all_urls>chrome-extension://*抛出错误:权限“chrome-extension://*”未知或 URL 模式格式错误。但以上都不起作用。
此外,results.js注入后应该发送消息以background.js获取响应一些数据以供输入results.html。
我的代码:
清单.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"]
}
Run Code Online (Sandbox Code Playgroud)
背景.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});
}
}
Run Code Online (Sandbox Code Playgroud)
结果.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*/
}
);
Run Code Online (Sandbox Code Playgroud)
小智 2
您需要在manifest.json中添加host_permissions。在manifest.json中添加主机权限的示例
"host_permissions":["*://ahainstructornetwork.americanheart.org/"]
查看这篇文章了解详细信息:https://developer.chrome.com/docs/extensions/mv3/declare_permissions/#host-permissions
| 归档时间: |
|
| 查看次数: |
9655 次 |
| 最近记录: |