I'm trying to create a chrome extension that copies a value from tab A and pastes it on tab B. I'm trying to make it work but I get no response message back. Here's my code:
content-script.js
var toCopy = "Copy: I am a String";
document.getElementById('btnCopy').onclick = doCopy;
function doCopy(){
chrome.runtime.sendMessage(extId, {text: toCopy}, chrome => {
console.log('Copied ' + toCopy + '!');
});
}
var toPaste = "Get: textCopied";
document.getElementById('btnPaste').onclick = doPaste;
function doPaste(){
chrome.runtime.sendMessage(extId, {text: toPaste}, chrome => {
console.log('Pasted ' + toPaste + '!');
});
}
background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.text.substring(0, 5) === "Copy:")
chrome.storage.sync.set({'textCopied': text.substring(6, text.length)}, function () {
console.log('saved!');
});
else if (message.text.substring(0, 4) === "Get:")
chrome.storage.sync.get(['textCopied'], function (items) {
console.log('Here is the copied text from before: ' + items);
});
}
The context:
I have defined 'inject.js' on my manifest.json. Once that 'inject.js' is run, it appends a new file 'file1.js' to the header of the target page. 'file1.js' has chained functions to replace and reorder some of the fields in that target page, and, it has too the function of the 'Copy' button which I want to use for copying a value from the tab that's running with the extension to another tab that I will open later. So, I have the copy function defined in 'file1.js' and not in 'inject.js'. If I define the 'chrome.storage.sync.set' statement in 'inject.js' it works great but I want/need to execute the function once a button is clicked. That button appears when 'file1.js' script is run (because inside 'file1.js' I create and append the copy button) so I think I must define the button action inside 'file1.js' script, right? Or can I call the function from 'inject.js' with the button I've created using 'file1.js'?
The answer:
I just put everything into 'inject.js' and now its working like a charm. Vouch for wOxxOm who helped me with this!
(see answers for more information)