tap*_*and 11 javascript google-chrome google-chrome-extension
我正在编写一个chrome扩展,它检测正在打开的文件类型,并在页面上注入一个执行许多其他操作的脚本.以下是我注入脚本的background.js代码的一部分:
chrome.webRequest.onHeadersReceived.addListener(function(details){
console.log("Here: " + details.url + " Tab ID: " + details.tabId);
if(toInject(details))
{
console.log("PDF Detected: " + details.url);
if(some-condition)
{
//some code
}
else
{
chrome.tabs.executeScript(details.tabId, { file: "contentscript.js", runAt: "document_start"}, function(result){
if(chrome.runtime.lastError)
{
console.log(chrome.runtime.lastError.message + " Tab ID: " + details.tabId);
}
});
}
return {
responseHeaders: [{
name: 'X-Content-Type-Options',
value: 'nosniff'
},
{
name: 'X-Frame-Options',
/*
Deny rendering of the obtained data.
Cant use {cancel:true} as we still need the frame to be accessible.
*/
value: 'deny'
}]
};
}
}, {
urls: ['*://*/*'],
types: ['main_frame', 'sub_frame']
}, ['blocking', 'responseHeaders']);
Run Code Online (Sandbox Code Playgroud)
这是清单文件:
{
"manifest_version": 2,
"name": "ABCD",
"description": "ABCD",
"version": "1.2",
"icons": {
"16" : "images/16.png",
"32" : "images/32.png",
"48" : "images/48.png",
"128" : "images/128.png"
},
"background": {
"scripts": ["chrome.tabs.executeScriptInFrame.js", "background.js"],
"persistent": true
},
"permissions": [
"webRequest",
"<all_urls>",
"webRequestBlocking",
"tabs",
"nativeMessaging"
],
"web_accessible_resources": [ "getFrameId", "aux.html", "chrome-extension:/*", "images/*.png", "images/*.gif", "style.css"]
}
Run Code Online (Sandbox Code Playgroud)
问题是,当注入脚本时,最后一个错误部分运行,它显示选项卡已关闭,脚本未注入.如果我按下多功能框上的输入几次注入脚本并且工作正常.以下是一系列事件:
抱歉我的天真照片编辑:P
我们可以从这张图片中推断出更多的东西:
chrome.runtime与background.js连接的脚本断开连接.几天来,我一直在为此而奋斗.关于SO的其他问题没有解决这个问题.也不是互联网上的任何其他地方.
编辑:
还有一点需要注意:上图中显示的样本运行就是这样的.有许多不同的行为.有时3次进入不会使其发挥作用.有时只会一个人.因为我发送的自定义标题有什么问题吗?
更新#1
必须注意我要返回的标题OnHeadersReceived.这样做是为了阻止chrome渲染文档.但是在这样做时,文件的所有数据都被转储到屏幕上,我不希望它出现.所以我认为我需要document_start这样,以便在我的内容脚本执行其他操作(例如在页面上放置自定义UI)之前隐藏转储的数据.
更新#2
注意到还有一件事.如果我打开一个新标签,然后在那里粘贴一个网址,然后按回车键,以下是控制台上后台页面的输出.
所以我猜,窗口的位置稍后会被chrome更新.我对吗?任何解决方法?
"The tab was closed"错误消息有点误导,因为该选项卡显然没有关闭。在 chrome 源中,带有字符串的变量称为kRendererDestroyed。所以错误是因为相应的渲染器由于某种原因被破坏。
如果在选项卡中打开的页面重定向(因此一个渲染器被破坏,为同一选项卡创建了另一个渲染器,但这次的 URL 不同),我会收到错误,在这种情况下,扩展将获得选项卡更新,其状态如下:
loadingurl: 'example.com',此处选项卡已返回回调等,但如果尝试注入脚本,则会收到错误loading网址:'example.com/other_url'title: 'some title'complete我设法通过仅在接收后注入脚本来解决status: 'complete'(但可能注入title也应该这样做)
没有尝试使用 pdf,但 chrome 可能会用重定向替换那些渲染器。因此,请更多地关注页面状态和重定向/渲染器替换。希望这可以帮助任何遇到这个问题的人。