我正在开发一个Chrome扩展,我需要将突出显示的文本传递到browser_action中。我在Google中找到了下面的代码,在编写时它仍然有效--但是它不再工作了。
有人知道另一种解决办法吗?
background.html:
<html>
<head>
<script type="text/javascript">
var selection_callbacks = [];
function getSelection(callback) {
selection_callbacks.push(callback);
chrome.tabs.executeScript(null, { file: "contentscript.js" });
};
chrome.extension.onRequest.addListener(function (request) {
var callback = selection_callbacks.shift();
callback(request);
});
</script>
</head>
<body>
</body>
</html>
popup.html:
<html>
<head>
<script type="text/javascript">
function onSelection(text) {
document.getElementById("output").innerHTML = text;
}
chrome.extension.getBackgroundPage().getSelection(onSelection);
</script>
</head>
<body>
<div id="output">
This should be replaced with the selected text
</div>
</body>
</html>
contentscript.js:
chrome.extension.sendRequest(window.getSelection().toString());
发布于 2010-03-06 20:03:52
您可以使用一个真正的内容脚本,而不是用chrome.extension.executeScript将JavaScript注入页面。然后,您可以让background.html使用chrome.tabs.sendRequest请求内容脚本进行选择。
https://stackoverflow.com/questions/2385862
复制相似问题