问题描述
扩展的清单文件
{
"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"]
}
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');
// }
}
从 content.js 文件接收消息并将其传递给 popup.js 文件
// 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 模板
<!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>
popup.js 文件,我想在其中通过 dom 方法操作突出显示的元素
var word = chrome.extension.getBackgroundPage().word;
console.log(word);
// const selectedButton = document.getElementById('highlight');
// const heading = document.getElementById('h');
// selectedButton.addEventListener('click',() => {});
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)