use*_*011 5 javascript selection google-chrome-extension
我花了几个小时在网上搜索解决方案.我想做的是将页面上突出显示的文本转移到chrome扩展名的popup.html中的textarea.我想知道是否有人可以为我提供可以执行此操作的扩展程序的建议源代码.
这是我认为最有用的最相关的线程 - 查询类似.弹出窗口中的按钮,用于获取所选文本 - Chrome扩展程序
我尝试复制代码并将其作为扩展名运行,但它没有获得突出显示的文本.想知道是否有人有任何建议以及如何解决这个问题.非常感谢你.
Bea*_*ist 15
就像您链接的问题的答案一样,您将需要使用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>
Run Code Online (Sandbox Code Playgroud)
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;
});
});
}
Run Code Online (Sandbox Code Playgroud)
selection.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
Run Code Online (Sandbox Code Playgroud)
的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
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是源文件的链接.
弹出窗口.js
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
alert(selection[0]);
});
Run Code Online (Sandbox Code Playgroud)
清单文件
"permissions": [
"activeTab",
],
Run Code Online (Sandbox Code Playgroud)
看看这个简单的扩展https://github.com/kelly-apollo/zdic
| 归档时间: |
|
| 查看次数: |
11143 次 |
| 最近记录: |