【发布时间】:2019-06-10 01:35:32
【问题描述】:
我找到了有关如何获取当前选项卡的页面源的答案: Getting the source HTML of the current page from chrome extension
但是,这个答案需要用户按下扩展弹出窗口。
我想知道如何在加载页面时访问页面源(无需调用弹出窗口)。
在我的background.js 我已经厌倦了这个:
chrome.tabs.onUpdated.addListener(function (tabId , info) {
console.log(info)
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
});
但这会导致以下错误:
注入脚本时出错:无法访问 页。扩展清单必须请求访问权限 各自的主机。
我的manifest.js:
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"permissions": ["declarativeContent",
"https://www.example.com/*",
"storage",
"activeTab"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"options_page": "options.html",
"manifest_version": 2,
"page_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
},
"icons": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
}
我认为问题不在于权限,因为我能够从 popup.html(即 page_action 脚本)获取页面源。但我无法通过“背景”或“内容脚本”获得它。为什么会这样?实现这一目标的正确方法是什么?
【问题讨论】:
标签: google-chrome google-chrome-extension google-chrome-devtools