我正在创建一个 chrome 扩展来存储用户突出显示的文本,并将其在扩展的弹出窗口中可用。我正在尝试使用同步或本地将突出显示的文本(字符串)存储在 chrome 存储中,然后在弹出窗口中获取它。另外,我创建了一个数组来存储字符串。
使用 chrome 存储有什么建议或最佳实践吗?还是通过消息传递更好?(将字符串数组发送到弹出窗口)
清单.json
{
"manifest_version": 2,
"name": "Information Hoover",
"version": "0.1",
"description": "Grab and store knowledge around the web",
"permissions": ["activeTab", "tabs", "declarativeContent", "storage", "contextMenus"],
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_popup": "popup.html",
"default_title": "get highlighted text"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
]
}
内容.js
let texts = [];
window.addEventListener('mouseup', getSelectionText);
function getSelectionText(){
let selectedText = window.getSelection().toString();
if (selectedText.length > 0){ // check there's some text selected
let message = {
text: selectedText
};
//chrome.runtime.sendMessage(message);
texts.push(selectedText);
console.log(message);
}
}
背景.js
chrome.runtime.onMessage.addListener(receiver);
let highlightedTexts = [];
function receiver(request, sender, sendResponse) {
sentence = request.text;
highlightedTexts.push(sentence);
console.log(highlightedTexts);
}
popup.js
function setup() {
let bgpage = chrome.extension.getBackgroundPage();
let texts = [];
let word = bgpage.sentence;
texts.push(word);
document.querySelector('.selectedtext').innerHTML = word;
console.log(texts);
}
setup();
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="selected-text-area">
<p class="selectedtext"> </p>
</div>
<script src="popup.js"></script>
</body>
</html>