我花了几个小时在网上搜索解决方案。我想做的是将页面上突出显示的文本转移到chrome扩展名的popup.html中的textarea。我想知道是否有人可以为我提供可以执行此操作的扩展程序的建议源代码。
这是我看过的最相关的线程,我认为最有用 - 查询类似。 Button in popup that get selected text - Chrome extension
我尝试复制代码并将其作为扩展名运行,但它没有获得突出显示的文本。想知道是否有人有任何建议以及如何解决这个问题。非常感谢你。
答案 0 :(得分:13)
就像您关联的问题的答案一样,您需要使用Message Passing和Content Scripts。该代码已超过2年,并使用了onRequest
和getSelected
等折旧方法。一些简单的修改应该足以将其更新为新的api。
Popup.html
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.8.3.min.js"></script>
<script src="popup.js"></script>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
</head>
<body>
<textarea id="text"> </textarea>
<button id="paste">Paste Selection</button>
</body>
</html>
popup.js(以便没有任何内联代码)
$(function(){
$('#paste').click(function(){pasteSelection();});
});
function pasteSelection() {
chrome.tabs.query({active:true, windowId: chrome.windows.WINDOW_ID_CURRENT},
function(tab) {
chrome.tabs.sendMessage(tab[0].id, {method: "getSelection"},
function(response){
var text = document.getElementById('text');
text.innerHTML = response.data;
});
});
}
selection.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
的manifest.json
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"manifest_version": 2,
"browser_action": {
"default_title": "Selected Text",
"default_icon": "online.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["selection.js"],
"run_at": "document_start",
"all_frames": true
}
]
}
Here是源文件的链接。
答案 1 :(得分:2)
popup.js
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
alert(selection[0]);
});
的manifest.json
"permissions": [
"activeTab",
],
看看这个简单的扩展程序https://github.com/kelly-apollo/zdic