drmrbrewer
drmrbrewer

Reputation: 13009

navigator.clipboard is undefined

Why is navigator.clipboard always undefined in the following snippet?

var clipboard = navigator.clipboard;
if (clipboard == undefined) {
    console.log('clipboard is undefined');
} else {
    clipboard.writeText('stuff to write').then(function() {
        console.log('Copied to clipboard successfully!');
    }, function() {
        console.error('Unable to write to clipboard. :-(');
    });
}

More on the clipboard API can be found here.

Chrome Version: 68.0.3440.106.

I'm sure this was working at some point, but no longer is. It's confusing because this table suggests that the Clipboard API is implemented in Chrome (has been for some time), but this table of specific API methods suggests that none of the methods of the API is supported??

Upvotes: 223

Views: 221233

Answers (9)

Adán Escobar
Adán Escobar

Reputation: 4643

as mentioned early "Clipboard API" only works in secure context.

in prod environment you need enable https, in order to works.

How to use in localhost:

If you want to enable for your local dev env, you need enable secure context first:

Enable Insecure origins treated as securein Chrome:

use this url in chrome:

chrome://flags/#Insecure-origins-treated-as-secure

then add your local domains and enable:

enter image description here

maybe you need re-start chrome

then when your visit your site allow copy

enter image description here

now you able to use:

navigator.clipboard.readText().then(pastedData => {
        console.log(pastedData);
});

Upvotes: 7

Kiritushka
Kiritushka

Reputation: 1140

const copy = (text: string) => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text)
  } else {
    const input = document.createElement('textarea')
    input.value = text
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
  }
}

Upvotes: 4

Simon Dehaut
Simon Dehaut

Reputation: 2651

You can write an all-in-one wrapper function.

  • if in secure context (https): use navigator clipboard api
  • if not: use the 'out of viewport hidden text area' trick
async function copyToClipboard(textToCopy) {
    // Navigator clipboard api needs a secure context (https)
    if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(textToCopy);
    } else {
        // Use the 'out of viewport hidden text area' trick
        const textArea = document.createElement("textarea");
        textArea.value = textToCopy;
            
        // Move textarea out of the viewport so it's not visible
        textArea.style.position = "absolute";
        textArea.style.left = "-999999px";
            
        document.body.prepend(textArea);
        textArea.select();

        try {
            document.execCommand('copy');
        } catch (error) {
            console.error(error);
        } finally {
            textArea.remove();
        }
    }
}

Usage:

try {
    await copyToClipboard("I'm going to the clipboard !");
    console.log('Text copied to the clipboard!');
} catch(error) {
    console.error(error);
}

PS: do not try it in a repl like jsfiddle/copeden/...  

Upvotes: 159

Lutfi Fahmani
Lutfi Fahmani

Reputation: 35

you can use :

change the :

navigator.clipboard.writeText("Content")

to : navigator['clipboard'].writeText("Content") instead.

Upvotes: -4

Laurent Lyaudet
Laurent Lyaudet

Reputation: 948

A minimal solution for copying tooltips when HTTPS is not yet available and the solution with document.execCommand('copy') does not work. But it requires that the user selects and copies by hand what is displayed in the alert.

function copyToClipboard(text) {
    if(navigator.clipboard) {
        navigator.clipboard.writeText(text);
    }
    else{
        alert(text);
    }
}

Upvotes: 6

Ramkrishna Bhatt
Ramkrishna Bhatt

Reputation: 61

In localhost, the clipboard is blocked by the chrome browser. You check this by going to the following path

Chrome > settings > privacy and Security > site settings > View permissions and data stored across sites then click on your localhost URL which will mentation on the page and check the permission of the clipboard

Upvotes: 6

jazkat
jazkat

Reputation: 5798

This solutions works at the moment (it includes cross browser support, error handling + clean up).

https://stackoverflow.com/a/33928558/318380

Upvotes: 2

Juliano Costa
Juliano Costa

Reputation: 525

Try this:

if (typeof (navigator.clipboard) == 'undefined') {
    console.log('navigator.clipboard');
    var textArea = document.createElement("textarea");
    textArea.value = linkToGo;
    textArea.style.position = "fixed";  //avoid scrolling to bottom
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        toastr.info(msg);
    } catch (err) {
        toastr.warning('Was not possible to copy te text: ', err);
    }

    document.body.removeChild(textArea)
    return;
}
navigator.clipboard.writeText(linkToGo).then(function () {
    toastr.info(`successful!`);
}, function (err) {
    toastr.warning('unsuccessful!', err);
});

Upvotes: 18

Josh Lee
Josh Lee

Reputation: 177614

This requires a secure origin — either HTTPS or localhost (or disabled by running Chrome with a flag). Just like for ServiceWorker, this state is indicated by the presence or absence of the property on the navigator object.

https://developers.google.com/web/updates/2018/03/clipboardapi

This is noted in the spec with [SecureContext] on the interface: https://w3c.github.io/clipboard-apis/#dom-navigator-clipboard

You can check the state of window.isSecureContext to learn if that's the reason a feature is unavailable. Secure contexts | MDN

And yes, you should set up HSTS to make sure HTTP redirects to HTTPS.

Upvotes: 308

Related Questions