我正在开发一个 chrome 扩展程序,它涉及获取当前选项卡的选定文本。这是我使用的 html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.getElementById("output").value = selection[0];
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
它不起作用,为什么?以下是来自 Chrome App & Extension Developer Tool 的错误信息,其中一些错误信息被省略号 chop 了,抱歉,我还没有弄清楚如何在这里查看完整的错误信息,查看详细信息 只给我堆栈轨迹,而不是完整的错误消息。
最佳答案
正如@Xan 所建议的,前面提到的方法(您可以找到它 here )过于复杂。要使其正常工作,只需要做两件事:
在
中将document.getElementById("output").value
value
更改为innerHTML
在
manifest.json
文件中添加activeTab
权限
这里是完整的源码,一共三个文件。
list .json
{
"manifest_version": 2,
"name": "sample",
"description": "A sample extension to get the selected text",
"version": "1.0",
"icons": {
"16": "img/icon16.png",
"48": "img/icon48.png",
"128": "img/icon128.png"
},
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="popup.js"></script>
<title></title>
</head>
<body>
<div id="output"></div>
</body>
</html>
弹窗.js
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.getElementById("output").innerHTML = selection[0];
});
关于javascript - 如何在 chrome 扩展开发中获取选定的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34170032/