我正在尝试为chrome做一个简单的测试扩展。这是应该发生的情况:
问题是按下扩展按钮时,文本将被取消选择,因此警报什么也没有显示。我已经阅读了许多与此问题相关的StackOverflow答案,但是我是JS新手,无法弄清楚。
这些是我的文件:
manifest.json
{
"name": "Test",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": ["<all_urls>"],
"js":["content.js"],
}
],
"browser_action":{
"default_popup": "popup.html",
"default_title": "Text Finder"
}
}
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button>Show Text</button>
<script src="popup.js" charset="ut-8"></script>
</body>
</html>
popup.js
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', onclick, false)
function onclick () {
chrome.tabs.query({currentWindow: true, active: true},
function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, getSelectionText())
}
)
}
}, false)
content.js
chrome.runtime.onMessage.addListener(function (request){
alert(request)
})
更好的方法是在上下文菜单中添加一个项目。为此,用户将选择某些内容,然后单击鼠标右键,然后选择您的菜单条目以将选择内容发送到您的分机。
chrome.contextMenus.create(
id : 'selectionGetter',
title : 'send selected text',
contexts : ['selection'],
);
chrome.contextMenus.onClicked.addListener(function (info,tab) {
//showing alert would require you to send a message to the active tab,
//handle it in the contentscript and send alert from there
//alternate lazy usage example:
new Notification('My extension',{
body : 'you selected: '+info.selectionText,
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句