Chrome extension: copy text

I have a simple chrome extension where I would like to click an image and copy the href links next to it. I have everything in place, but the copy will not work for me. I have the following prerequisites in my manifest:

"Permissions": ["ClipboardRead", "ClipboardWrite"]

Then I create an input with the identifier "copyInp" and use the following function to copy to the clipboard (I tried to be as intentional as possible here, so it is not the most compact):

function copyLinkToClipboard( link ) { $("#copyInp").val(link); var inp = document.getElementById("copyInp"); inp.focus(); inp.select(); document.execCommand('copy'); 

};

After that, I get nothing new in my clipboard when I ctrl + v. Any ideas on what's going on here? The input definitely has the text that I want in it, and I have permission in the manifest. Any help would be greatly appreciated ...

+4
source share
1 answer

After digging a little more, I found that I needed to use a wallpaper. Apparently this is the only thing you can call document.execCommand. Thus, the fix is ​​to create background.html with the copy and input function in it, add a listener like this:

 chrome.extension.onRequest.addListener(function(obj) { copyLinkToClipboard( obj.link ); }); 

and then use sendRequest to pass the text you want to copy to the original page:

 chrome.extension.sendRequest({link: linkText}); 

and don't forget to add the background image to the manifest

 "background_page": "background.html", 

voila. The text is copied to the clipboard. LOVE would be an easier way to do this (if security is a problem, why not make an api for extensions? Or rather, why break an experimental api just to make us make this stupid workaround?), But well, this will be enough for time

+7
source

Source: https://habr.com/ru/post/1390109/


All Articles