Chrome 扩展-获取 DOM 内容

我正试图从弹出窗口访问 activeTab DOM 内容:

{
"manifest_version": 2,


"name": "Test",
"description": "Test script",
"version": "0.1",


"permissions": [
"activeTab",
"https://api.domain.com/"
],


"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",


"browser_action": {
"default_icon": "icon.png",
"default_title": "Chrome Extension test",
"default_popup": "index.html"
}
}

我真的很困惑,后台脚本(带有持久性: false 的事件页面)还是 content _ script 才是正确的选择。我已经阅读了所有的文档和其他的职位,它仍然对我没有意义。

有人能解释一下为什么我会用一个而不是另一个吗。

以下是我一直在尝试的背景:

chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
// LOG THE CONTENTS HERE
console.log(request.content);
}
);

我只是在弹出控制台上执行:

chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, { }, function(response) {
console.log(response);
});
});

我得到了:

Port: Could not establish connection. Receiving end does not exist.

更新:

{
"manifest_version": 2,


"name": "test",
"description": "test",
"version": "0.1",


"permissions": [
"tabs",
"activeTab",
"https://api.domain.com/"
],


"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],


"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",


"browser_action": {
"default_icon": "icon.png",
"default_title": "Test",
"default_popup": "index.html"
}
}

Content js

chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.text && (request.text == "getDOM")) {
sendResponse({ dom: document.body.innerHTML });
}
}
);

Popup.html

chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, { action: "getDOM" }, function(response) {
console.log(response);
});
});

当我运行它时,仍然会得到相同的错误:

undefined
Port: Could not establish connection. Receiving end does not exist. lastError:30
undefined
227352 次浏览

术语“背景页面”、“弹出窗口”、“内容脚本”仍然让您感到困惑; 我强烈建议您更深入地了解 谷歌 Chrome 扩展文档

关于你的问题,如果内容脚本或背景页面是去的方式:

内容脚本 : 当然
内容脚本是可以访问网页 DOM 的扩展的唯一组件。

背景页/弹出窗口 : 可能(可能是两者中的最大值)
您可能需要让内容脚本将 DOM 内容传递到后台页面或弹出窗口以进行进一步处理。


让我重复一遍,我强烈建议您更仔细地研究可用的文档!
也就是说,这里有一个示例扩展,它检索 StackOverflow 页面上的 DOM 内容并将其发送到后台页面,后台页面将在控制台中打印出来:

背景介绍:

// Regex-pattern to check URLs against.
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;


// A function to use as callback
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n' + domContent);
}


// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
// ...check the URL of the active tab against our pattern and...
if (urlRegex.test(tab.url)) {
// ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
}
});

Content.js:

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.text === 'report_back') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.all[0].outerHTML);
}
});

Json:

{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
...


"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.stackoverflow.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},


"permissions": ["activeTab"]
}

您不必使用消息传递来获取或修改 DOM。我用的是 chrome.tabs.executeScript。在我的示例中,我只使用 activeTab 权限,因此脚本只在活动选项卡上执行。

宣言的一部分 Json

"browser_action": {
"default_title": "Test",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]

Html

<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="test">TEST!</button>
<script src="test.js"></script>
</body>
</html>

Test Js

document.getElementById("test").addEventListener('click', () => {
console.log("Popup DOM fully loaded and parsed");


function modifyDOM() {
//You can play with your DOM here or check URL against your regex
console.log('Tab script:');
console.log(document.body);
return document.body.innerHTML;
}


//We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
}, (results) => {
//Here we have just the innerHTML and not DOM structure
console.log('Popup script:')
console.log(results[0]);
});
});

对于那些谁尝试 galpak 答案,它没有工作,

请注意,chrome 将添加内容脚本到一个需要的页面,只有当您的扩展启用在 chrome 启动期间,也是一个好主意重新启动浏览器后,作出这些更改