![](/img/trans.png)
[英]chrome extension - send message from content script to background page and back to content script?
[英]Chrome Extension - How to message DOM from content script to background page?
我要做的就是复制以chrome扩展名工作的文本。 我找到了这个答案, 在chrome扩展程序中正确使用了execcommand(“ paste”) ,它提供了以下copy()函数:
function copy(str) {
var sandbox = $('#sandbox').val(str).select();
document.execCommand('copy');
sandbox.val('');
}
问题是,如果我将其放在背景页面上并调用它,将无法正常工作,因为背景页面无法访问DOM元素(并且无法访问$('#sandbox'))。 因此,如何将content.js(可以访问DOM)脚本中的DOM元素$('#sandbox')发送到background.js脚本中?
我想出了如何将消息从content.js脚本发送到background.js脚本并通过以下方法接收响应:
content.js:
$('#copybutton').click(function(){
chrome.runtime.sendMessage({callCopyFunc: "callstart"}, function(response) {
console.log(response.callCopyFunc);
});
});
background.js:
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
if(request.callCopyFunc == "callstart"){
sendResponse({callCopyFunc: "callfinished"});
}
});
效果很好! 当我单击网页上的“ copybutton”元素(只是一个按钮)时,content.js将“ callstart”发送到background.js,background.js发送回“ callfinished”,然后将其显示在控制台日志中。
我的问题是:如何从content.js将DOM元素$('#sandbox')发送到background.js文件,以便可以在后台页面本身上使用copy()函数? 我不了解如何实际发送元素,仅发送文本。
抱歉,如果这真的很简单,我已经坚持了两天。 谢谢!
在花了几个小时花时间进行简单的chrome剪贴板API调用之后,我找到了一个解决方案。 我认为没有人真正需要它,但是无论如何我都会将其发布在这里,因为我在解决方案上花费了太多时间。
我在chrome应用商店上下载了“ plus for trello”,并查看了它的代码。 本质上,所有复制功能都是在background.html(背景页面)和background.js(背景页面中包含的脚本)上完成的。
在清单中,您需要这两件事:
"background": {
"page": "background.html",
"persistent": true
},
"permissions":["clipboardWrite"],
然后在您的background.html页面中,您需要包含background.js脚本,还需要包含一个ID为您将在background.js脚本中使用的div:
<html>
<head>
<title></title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="background.js"></script>
</head>
<body>
<div id="selectionPlaceholder"></div>
</body>
</html>
然后,在您的background.js脚本(包括在background.html中)中,您需要此功能(我从“ plus for trello”扩展名获得此功能):
function handleCopyClipboard(html) {
if (window.getSelection && document.createRange) {
var elemReplace = document.getElementById("selectionPlaceholder");
elemReplace.innerHTML = html; //This is what it will copy
var sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(elemReplace);
sel.removeAllRanges();
sel.addRange(range);
document.execCommand("Copy");
elemReplace.innerHTML = ""; //blank it when done
return;
}
}
并且您需要向该函数传递一些文本。 我使用我在原始帖子中描述的runetime.onMessage消息传递系统从content.js脚本传递了文本。 可以直接从background.js调用它,因为此脚本可以访问您的background.html页面(包含在其中)。
编辑:而且,如果您更喜欢较短的copy()函数,则可以在background.html页面上包含jquery.js,在background.html页面上包含<textarea id="sandbox></textarea>
从background.js文件中调用copy()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.