Is it possible to open a new browser tab after content has been copied into the clipboard?
Currently I'm getting Uncaught (in promise) DOMException: Document is not focused.
which I take it that I can't open a new window within the function as I know the tab has to be active for copy to clipboard to work (without permissions).
https://web.dev/async-clipboard/
Do I need to run the code outside the function somehow ie. event or observer to detect when copyToClipboard function has been executed? Or any other way to run it in the function and ensure writing to clipboard is finished before the new window opens? (I tried even setTimeout to no avail).
HTML
<body>
<button type=button onclick="copyToClipboard()">Copy</button>
<div id="template">
Test
</div>
</body>
Js
function copyToClipboard(){
try {
const htmlCode = template.innerHTML;
const blobInput = new Blob([htmlCode], { type: 'text/html' })
navigator.clipboard.write([new ClipboardItem({ 'text/html': blobInput })])
alert('Copied')
var win = window.open('https://mail.google.com/mail/', '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
} catch (e) {
alert(e)
}
};
I also tried using .then after navigator with same issue
navigator.clipboard.write([new ClipboardItem({ 'text/html': blobInput })]).then( window.open('https://mail.google.com/mail/', '_blank') );
UPDATE
Found out I need to use async and await, that worked! https://stackoverflow.com/a/72990164/8719001
async function openurl() {
await navigator.clipboard.writeText('TextToCopy');
window.open('url');
}