Can't select if iframe context?

(Daniel Dawson) #1

In order to copy some text into the clipboard, I have some code in a content script like this:

let copyBox = document.createElement("input");
copyBox.type = "text";
copyBox.style.display = "block";
copyBox.style.position = "absolute";
copyBox.style.top = "-1000px";
copyBox.style.left = "-1000px";
copyBox.style.opacity = "0";
copyBox.value = url;
document.body.appendChild(copyBox);
copyBox.select();
document.execCommand("copy");
document.body.removeChild(copyBox);

(BTW, is there a better way to do this than going through an invisible element?)

This is run ultimately from a context menu command. It works fine as long as the target is in the same document. But if it’s in an iframe, I find the selection usually doesn’t work, even though the element being created is outside the iframe. Or maybe because of that? What can I do to fix this?

(Martin Giger) #2

You can use https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard as an extension.

The context menu event gives you the frameId where the element that was targeted is. That way you can inject the script where it’s needed resp. send the message to the script in the correct frame.

(Daniel Dawson) #3

You can use https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard as an extension.

Right. I’ll do that. I don’t remember it being available when I was doing most of the development on this add-on. It’s good that it is now.

The context menu event gives you the frameId where the element that was targeted is. That way you can inject the script where it’s needed resp. send the message to the script in the correct frame.

Turns out this is unnecessary with the above. I can use the Clipboard API without involving a content script.

Thanks for the help.

1 Like