我有一个基本的 Chrome 扩展程序,需要通过弹出窗口访问网页的 document.body
。
目前,当我尝试打开弹出窗口和控制台日志 document.body
时,它会记录弹出窗口的 document.body
,而我想要网站的 document.body
.
我该怎么做?
manifest.json
{
"description": "Demo ext",
"manifest_version": 2,
"name": "Demo ext",
"version": "1.0",
"icons": {
"48": "icons/icon-48.png"
},
"permissions": ["activeTab"],
"browser_action": {
"default_icon": "icons/icon-32.png",
"theme_icons": [
{
"light": "icons/icon-32-light.png",
"dark": "icons/icon-32.png",
"size": 32
}
],
"default_title": "Demo ext",
"default_popup": "popup/index.html"
}
}
弹出/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo ext</title>
</head>
<body>
<h1>Title should be the websites which we are on 👇</h1>
<script src="./app.js"></script>
</body>
</html>
弹出/app.js
function main() {
console.log(document.body)
var title = document.createElement('div')
title.innerHTML = document.title
document.body.appendChild(title)
}
main()
我希望此处记录的document.body
是网站的。我该怎么做?
最佳答案
我建议您查看此Chrome Extension Content Scripts
If your extension needs to interact with web pages, then it needs a content script. A content script is some JavaScript that executes in the context of a page that's been loaded into the browser. Think of a content script as part of that loaded page, not as part of the extension it was packaged with (its parent extension).
内容脚本可以通过与扩展程序交换消息来访问其父扩展程序使用的 Chrome API。他们还可以使用 chrome.runtime.getURL() 访问扩展文件的 URL,并像其他 URL 一样使用结果。
关于javascript - 使用 Chrome 扩展时从弹出窗口获取网页的 document.body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515568/