[英]How do I get the DOM from a webpage with Chrome Extension Manifest v3?
I'm making a chrome extension to gather data from a webpage.我正在制作一个 chrome 扩展来从网页收集数据。 When I try to use
document.querySelectorAll()
it gets the DOM from the popup, not the current webpage.当我尝试使用
document.querySelectorAll()
时,它从弹出窗口获取 DOM,而不是当前网页。 I tried using chrome's messaging system to request and send back the HTML but it doesn't work and gives me errors.我尝试使用 chrome 的消息系统来请求并发回 HTML,但它不起作用并且给我错误。
Here's the important files:以下是重要文件:
manifest.json
{
"name": "Name",
"description": "Description",
"version": "1.0",
"manifest_version": 3,
"permissions": ["storage", "activeTab", "scripting", "tabs"],
"host_permissions": [
"*://*.website.com/*"
],
"content_scripts": [
{
"matches": ["*://*.website.com/*"],
"js": ["content_script.js"]
}
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"32": "/images/icon.png"
}
},
"icons": {
"32": "/images/icon.png"
}
}
popup.js
(runs inside popup.html
) popup.js
(在popup.html
内运行)
function fetchData() {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "fetchData"}, (response) => {
console.log(response);
});
});
}
content_script.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting === "fetchData") {
sendResponse(document.querySelectorAll(".class"));
}
}
);
The error I get from the message sending is "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist."我从消息发送中得到的错误是“Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.”
When I turn the NodeList to an array, there are no console errors, but it returns a list of "[object Object]".当我将 NodeList 转换为数组时,没有控制台错误,但它返回“[object Object]”列表。
Please let me know if there's a way to do this.如果有办法做到这一点,请告诉我。 I'm just using vanilla js.
我只是在使用香草 js。
The problem is that NodeList
can not by default be serialized into JSON in Chrome.问题是
NodeList
在 Chrome 中默认不能序列化为 JSON。
from mdn web docs来自 mdn web 文档
sendResponse
A function to call, at most once, to send a response to the message.
最多调用一次 function 以发送对消息的响应。 The function takes a single argument, which may be any serializable object (see Data cloning algorithm ).
function 采用单个参数,可以是任何可序列化的 object(请参阅数据克隆算法)。 This argument is passed back to the message sender.
该参数被传回给消息发送者。
You should refer to this stackoverflow answer to json serialize a NodeList before sending it back to popup.js
您应该参考这个stackoverflow 对 json 的回答在将 NodeList 发送回
popup.js
之前序列化它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.