All I want to do is get copying text working in a chrome extension. I found this answer, the proper use of execcommand("paste") in a chrome extension, which gives this copy() function:
function copy(str) {
var sandbox = $('#sandbox').val(str).select();
document.execCommand('copy');
sandbox.val('');
}
The problem is, it doesn't work if I put that on the background page and call it because the background page doesn't have access to the DOM elements (and can't access $('#sandbox')). So how can I send the DOM element $('#sandbox') from my content.js (which can access the DOM) script to my background.js script?
I figured out how to send a message from my content.js script to my background.js script and receive a response through this:
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"});
}
});
That works great! When I click the "copybutton" element on my webpage (just a button), content.js sends "callstart" to background.js and background.js sends back "callfinished" which is then displayed in the console log.
My question is: How do I send the DOM element $('#sandbox') to the background.js file from content.js so I can use the copy() function on the background page itself? I'm not understanding how to actually send an element, only text.
Sorry if this is really simple, I've been stuck on this for two days. Thanks!