Javascript 如何将突出显示的元素传递到popup.js文件,以便我可以操纵它进行更改
扩展名的清单文件Javascript 如何将突出显示的元素传递到popup.js文件,以便我可以操纵它进行更改,javascript,google-chrome,google-chrome-extension,google-chrome-devtools,Javascript,Google Chrome,Google Chrome Extension,Google Chrome Devtools,扩展名的清单文件 { "manifest_version": 2, "name": "Bookmarker", "version": "1.0", "description": "Bookmark pages so that you can continue reading it next time", "browser_act
{
"manifest_version": 2,
"name": "Bookmarker",
"version": "1.0",
"description": "Bookmark pages so that you can continue reading it next time",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"permissions": ["activeTab"]
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1 id="h">Bookmark curent location</h1>
<button id="highlight">highlight</button>
<script src="popup.js"></script>
</body>
</html>
从content.js文件接收消息并将其传递到popup.js文件
// Look for a "mouse up event"
document.addEventListener('mouseup', selectedText);
// Handle the mouse up event
function selectedText(event) {
// See what text has been selected by the user
var selected = window.getSelection().anchorNode.parentNode;
console.log(selected);
// Make sure something actually was selected
// if (selected.length > 0) {
// Send the message to the background script
// Can't be sent to the pop-up as the pop-up might
// not be open
chrome.runtime.sendMessage({ word: selected });
// } else {
// console.log('error');
// }
}
// Listen for messages
chrome.runtime.onMessage.addListener(receiver);
// A "global" variable to store the word selected by the user
var word;
// Get the message from the content script
function receiver(request, sender, sendResponse) {
// Save the word
word = request.word;
}
console.log(word);
扩展名的popup.html模板
{
"manifest_version": 2,
"name": "Bookmarker",
"version": "1.0",
"description": "Bookmark pages so that you can continue reading it next time",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"permissions": ["activeTab"]
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1 id="h">Bookmark curent location</h1>
<button id="highlight">highlight</button>
<script src="popup.js"></script>
</body>
</html>
因此,您需要在内容脚本中处理它。如果我在内容脚本中处理它,那么每次加载页面时操作都会启动我需要一个按钮来执行操作有很多方法可以分割逻辑,因此您必须具有创造性:-)非常感谢您的帮助,我将尝试它