How to use Clipboard API in Safari async

Safari support the Clipboard API, but only when directly triggered by a user interaction. You can't write to the Clipboard in an async context. Or can you?

Wolfgang Rittner

Wolfgang Rittner

Updated : see Copy to Clipboard async using Clipboard API for a solution that works across Chrome, Safari and Firefox.

Some strings attached

Safari supports the Clipboard API for some time now, but it locks it down to only work when triggered by a direct user interaction. That sounds like a sensible precaution to keep malicious sites from messing with your clipboard contents: You can't use the Clipboard API detached from user interaction in Safari. You can't even use it async in a Promise that was triggered by a user interaction.

I ran into an issue, where I tried to fetch something and copy the response into the clipboard. This works fine in Chrome and Firefox:

But it does not work in Safari unfortunately, because the security measures kick in when we are trying to use the Clipboard API in an async context. The error messages is as eloquent as useless: Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

Make it work even with async functions

But not all hope is lost! After some digging I found something promising on Apple's developer forums . You can wrap the Promise in a way that Safari (and Chrome) would accept.

The solution is to not call the Clipboard API in an async context, but rather turn things around and give the Clipboard API the async Promise. This way the Clipboard API is called from a synchronous context directly triggered by user interaction. And the Clipboard API will deal with resolving the Promise internally. This involves creating a ClipboardItem and adding this to the clipboard instead of adding plain text to the clipboard.

Caveat: Not working in Firefox

Well, at least not out of the box. When testing my new solution, that worked so nicely with Safari and Chrome, on Firefox I was presented with yet another error message: ReferenceError: ClipboardItem is not defined .

The ClipboardItem class I used to wrap the Promise is supported by Firefox, but is behind the dom.events.asyncClipboard.clipboardItem preference, which is turned off by default. Back to square one, I guess. I'm going to try fixing this for Firefox next, stay tuned.

Update: see Copy to Clipboard async using Clipboard API for a solution that works across Chrome, Safari and Firefox.

How can I copy text to clipboard with JavaScript?

document.execcommand('copy') safari

A very common need when building websites is the ability to copy text to clipboard with a single button click. Doing this programmatically with JavaScript is quite easy in modern browsers, using the asynchronous Clipboard API . If, however, you need to support older browsers, there is an alternative option, but it's a little more complicated.

The Asynchronous Clipboard API

Full support for the Clipboard API still isn't here at the time of writing (January, 2024), but you can at least use it to write to the clipboard. Thankfully, that's all you really need. Despite support caveats, this is the recommended way to copy text to clipboard, as it provides an easy and secure solution.

All you have to do is ensure Navigator , Navigator.clipboard and Navigator.clipboard.writeText are truthy and then call Clipboard.writeText() to copy the value to clipboard. In case anything goes wrong, you can use Promise.reject() to return a promise that rejects immediately and keep the return type consistent.

If you're concerned about browser support, you can use Promise.prototype.catch() to handle the error and provide a fallback . The fallback could even be using the legacy method, which we'll cover next.

Using Document.execCommand('copy')

While support for the Clipboard API is pretty high across the board, you might need a fallback if you have to support older browsers . If that's the case, you can use Document.execCommand('copy') to do so. Here's a quick step-by-step guide:

  • Create a <textarea> element to be appended to the document. Set its value to the string you want to copy to the clipboard.
  • Append the <textarea> element to the current HTML document and use CSS to hide it to prevent flashing.
  • Use Selection.getRangeAt() to store the selected range (if any).
  • Use HTMLInputElement.select() to select the contents of the <textarea> element.
  • Use Document.execCommand('copy') to copy the contents of the <textarea> to the clipboard.
  • Remove the <textarea> element from the document and restore the user's previous selection, if any.

This method will not work everywhere, but only as a result of a user action (e.g. inside a click event listener). This is a security measure to prevent malicious websites from copying sensitive data to the clipboard without the user's consent.

More like this

document.execcommand('copy') safari

How can I redirect the page to HTTPS in JavaScript?

Learn how to redirect the page to HTTPS if it's currently in HTTP.

document.execcommand('copy') safari

How can I convert the data from an HTML form to a JavaScript object?

Convert the data from an HTML form into a JavaScript object or serialize it into a query string.

document.execcommand('copy') safari

How can I perform an HTTP request in JavaScript?

Learn how to perform HTTP GET, POST, PUT, and DELETE requests in JavaScript.

document.execcommand('copy') safari

How do I use JavaScript to modify the URL without reloading the page?

Learn all of the options JavaScript provides for modifying the URL of the current page in the browser without reloading the page.

Start typing a keyphrase to see matching snippets.

document.execcommand('copy') safari

Using JavaScript to copy text to the clipboard

document.execcommand('copy') safari

Providing users of a web application with a way of copying data to the system clipboard is a common requirement that can be achieved by employing some client-side JavaScript. This functionality is often needed so that users can copy some form of text, for example, a quotation or a block of code, without needing to manually select and copy the text manually.

As with any web application, you’ll need to consider what the browser support is for the APIs that you are working with. Ideally, you’ll write your code in such a way that it will work with as many browser versions as possible to maximise compatibility.

In this post, I will show you how to copy text to the clipboard using JavaScript in a way that is compatible with almost any browser in use today. I’ll also demonstrate alternative code that uses newer JavaScript features and therefore will only work in recent versions of modern browsers.

Code samples

Let’s dive straight in and see how we can implement the copy-to-clipboard functionality within a web application.

Maximum compatibility

We’re going to start with some code that aims to support as many browsers as possible.

The code below documents a copyTextToClipboard JavaScript function that should work in practically every browser that is still in use today. It’s hard to make guarantees, but the code should offer a very good level of support across as many browser versions as possible.

Let’s break down the above code into a manageable set of chunks, tackling each of the three main conditional sections within the function in the following sub-sections.

Note that depending on your scenario, the alert function calls may not be what you want. You may choose to remove these or replace them with console.log function calls instead.

Clipboard API

The copyTextToClipboard function first of all checks if the browser that is running the code has support for the Clipboard API by testing if navigator.clipboard is ‘ truthy ‘.

The Clipboard API is supported by most modern browsers. This includes Chrome and Firefox since 2018, as well as Edge and Safari since 2020. At the time of writing, CanIUse indicates that 94.18% of users can use the Clipboard API features.

Note that the Clipboard API is only available over HTTPS , non-secure pages will need to fall back to one of the alternative methods covered in the sub-sections that follow.

The writeText function is used to write the specified text to the clipboard. The writeText function is asynchronous and returns a Promise object once the contents of the clipboard have been updated. The promise will be rejected if the specified text cannot be written to the clipboard for any reason.

Note that it is also possible to wait for the result of the writeText function asynchronously via the await keyword. This is demonstrated later in the post.

Clipboard Data

If the Clipboard API is not available, the code tests if Clipboard Data can be accessed instead.

clipboardData can only be accessed directly on the window object by Internet Explorer .

The setData function is used to write text data to the clipboard by specifying the type of data as ‘Text’. The setData function is synchronous and will therefore return after the contents of the clipboard have been updated.

Note that Internet Explorer was retired on 15th June 2022 and can no longer be accessed directly on modern Windows operating systems that have recent Windows Updates installed. You may still find that users on older, unsupported operating systems such as Windows XP and Windows 7 may still be running Internet Explorer.

Copy command

As a fallback position, if neither the Clipboard API nor Clipboard Data are supported, the code will fall back to using document.execCommand to execute the ‘copy’ command, copying text from an off-screen Textarea .

Note that document.execCommand is a deprecated function, but it remains a well-supported feature across a wide range of browsers at the time of writing and is a good fallback position.

The Textarea style is updated to have a ‘fixed’ position with the top and left coordinates set to large minus values such that the Textarea will appear offscreen and therefore should not be visible to the user.

The textarea element is then temporarily added to the DOM body using the appendChild function and the Textarea is focused and selected so that its contents can be copied.

A try...catch statement wraps the next section of code where the document.execCommand function is called to execute the ‘copy’ command. The  document.execCommand function returns a Boolean object to indicate if the command was successful or not. Any exceptions that may be thrown will be caught by the catch block.

Lastly, the temporary textarea element is removed from the DOM body using the removeChild function. This action is done outside of a finally block to maximise browser compatibility.

It is most common for a copy-to-clipboard function to be triggered intentionally by the user through clicking a button on the user interface. It’s usually not a good idea to overwrite the user’s clipboard without their consent as there may be something important on their clipboard that they don’t want to lose!

The HTML below demonstrates how the copyTextToClipboard function can be triggered when a button is clicked by a user.

If this is the first time that the web application has attempted to copy data to the clipboard and the Clipboard API is being used, the user will see a prompt requesting if they want to grant the application access to the clipboard. An example of this prompt is shown below.

Clipboard access prompt

The user must press the ‘Allow’ button in order for the Clipboard API code to work.

Note that is also possible to check for and request the appropriate permission by using navigator.permissions  to work with the Permissions API .

Modern browsers

If you only plan to support modern browsers, you may choose to simplify the code by working solely with the Clipboard API. This could make sense when you are developing a web application where you have a lot of control over the browsers and associated browser versions that your users are using, or for cases where the copy-to-clipboard functionality is more of a ‘nice to have’ and it isn’t essential that the feature is available.

Below is a simplified example of how to copy text to the clipboard asynchronously via the Clipboard API.

The above code is using modern JavaScript ( ES6 ) features such as async functions and template literals .

Additionally, the above code is using the Module Pattern to keep the copyText function out of the global scope.

Below is an example of how to use the copyText function.

As mentioned earlier in this post, there may be changes that you will want to make to the code depending on your specific scenario, such as removing the alert function calls and/or adding logging, for example.

In this post, I covered how you can use JavaScript to copy text to the system clipboard.

I started by providing a code sample that aims to support the broadest possible range of browsers by using specific clipboard APIs when they are available and falling back to other methods that should work for older browser versions.

I also demonstrated how you would implement the code if supporting older browsers isn’t a concern for your application and you want to work with the latest JavaScript features instead.

I hope you enjoyed this post! Comments are always welcome and I respond to all questions.

If you like my content and it helped you out, please check out the button below 🙂

 Yes, add me to your mailing list.

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

Unblocking clipboard access

Safer, unblocked clipboard access for text and images

Jason Miller

The traditional way of getting access to the system clipboard was via document.execCommand() for clipboard interactions. Though widely supported, this method of cutting and pasting came at a cost: clipboard access was synchronous, and could only read and write to the DOM.

That's fine for small bits of text, but there are many cases where blocking the page for clipboard transfer is a poor experience. Time consuming sanitization or image decoding might be needed before content can be safely pasted. The browser may need to load or inline linked resources from a pasted document. That would block the page while waiting on the disk or network. Imagine adding permissions into the mix, requiring that the browser block the page while requesting clipboard access. At the same time, the permissions put in place around document.execCommand() for clipboard interaction are loosely defined and vary between browsers.

The Async Clipboard API addresses these issues, providing a well-defined permissions model that doesn't block the page. The Async Clipboard API is limited to handling text and images on most browsers, but support varies. Be sure to carefully study the browser compatibility overview for each of the following sections.

Copy: writing data to the clipboard

Writetext().

To copy text to the clipboard call writeText() . Since this API is asynchronous, the writeText() function returns a Promise that resolves or rejects depending on whether the passed text is copied successfully:

Browser Support

Actually, writeText() is just a convenience method for the generic write() method, which also lets you copy images to the clipboard. Like writeText() , it is asynchronous and returns a Promise.

To write an image to the clipboard, you need the image as a blob . One way to do this is by requesting the image from a server using fetch() , then calling blob() on the response.

Requesting an image from the server may not be desirable or possible for a variety of reasons. Fortunately, you can also draw the image to a canvas and call the canvas' toBlob() method.

Next, pass an array of ClipboardItem objects as a parameter to the write() method. Currently you can only pass one image at a time, but we hope to add support for multiple images in the future. ClipboardItem takes an object with the MIME type of the image as the key and the blob as the value. For blob objects obtained from fetch() or canvas.toBlob() , the blob.type property automatically contains the correct MIME type for an image.

Alternatively, you can write a promise to the ClipboardItem object. For this pattern, you need to know the MIME type of the data beforehand.

The copy event

In the case where a user initiates a clipboard copy and does not call preventDefault() , the copy event includes a clipboardData property with the items already in the right format. If you want to implement your own logic, you need to call preventDefault() to prevent the default behavior in favor of your own implementation. In this case, clipboardData will be empty. Consider a page with text and an image, and when the user selects all and initiates a clipboard copy, your custom solution should discard text and only copy the image. You can achieve this as shown in the code sample below. What's not covered in this example is how to fall back to earlier APIs when the Clipboard API isn't supported.

For the copy event:

For ClipboardItem :

Paste: reading data from clipboard

To read text from the clipboard, call navigator.clipboard.readText() and wait for the returned promise to resolve:

The navigator.clipboard.read() method is also asynchronous and returns a promise. To read an image from the clipboard, obtain a list of ClipboardItem objects, then iterate over them.

Each ClipboardItem can hold its contents in different types, so you'll need to iterate over the list of types, again using a for...of loop. For each type, call the getType() method with the current type as an argument to obtain the corresponding blob. As before, this code is not tied to images, and will work with other future file types.

Working with pasted files

It is useful for users to be able to use clipboard keyboard shortcuts such as ctrl + c and ctrl + v . Chromium exposes read-only files on the clipboard as outlined below. This triggers when the user hits the operating system's default paste shortcut or when the user clicks Edit then Paste in the browser's menu bar. No further plumbing code is needed.

The paste event

As noted before, there are plans to introduce events to work with the Clipboard API, but for now you can use the existing paste event. It works nicely with the new asynchronous methods for reading clipboard text. As with the copy event, don't forget to call preventDefault() .

Handling multiple MIME types

Most implementations put multiple data formats on the clipboard for a single cut or copy operation. There are two reasons for this: as an app developer, you have no way of knowing the capabilities of the app that a user wants to copy text or images to, and many applications support pasting structured data as plain text. This is typically presented to users with an Edit menu item with a name such as Paste and match style or Paste without formatting .

The following example shows how to do this. This example uses fetch() to obtain image data, but it could also come from a <canvas> or the File System Access API .

Security and permissions

Clipboard access has always presented a security concern for browsers. Without proper permissions, a page could silently copy all manner of malicious content to a user's clipboard that would produce catastrophic results when pasted. Imagine a web page that silently copies rm -rf / or a decompression bomb image to your clipboard.

Browser prompt asking the user for the clipboard permission.

Giving web pages unfettered read access to the clipboard is even more troublesome. Users routinely copy sensitive information like passwords and personal details to the clipboard, which could then be read by any page without the user's knowledge.

As with many new APIs, the Clipboard API is only supported for pages served over HTTPS. To help prevent abuse, clipboard access is only allowed when a page is the active tab. Pages in active tabs can write to the clipboard without requesting permission, but reading from the clipboard always requires permission.

Permissions for copy and paste have been added to the Permissions API . The clipboard-write permission is granted automatically to pages when they are the active tab. The clipboard-read permission must be requested, which you can do by trying to read data from the clipboard. The code below shows the latter:

You can also control whether a user gesture is required to invoke cutting or pasting using the allowWithoutGesture option. The default for this value varies by browser, so you should always include it.

Here's where the asynchronous nature of the Clipboard API really comes in handy: attempting to read or write clipboard data automatically prompts the user for permission if it hasn't already been granted. Since the API is promise-based, this is completely transparent, and a user denying clipboard permission causes the promise to reject so the page can respond appropriately.

Because browsers only allow clipboard access when a page is the active tab, you'll find that some of the examples here don't run if pasted directly into the browser's console, since the developer tools themselves are the active tab. There's a trick: defer clipboard access using setTimeout() , then quickly click inside the page to focus it before the functions are called:

Permissions policy integration

To use the API in iframes, you need to enable it with Permissions Policy , which defines a mechanism that allows for selectively enabling and disabling various browser features and APIs. Concretely, you need to pass either or both of clipboard-read or clipboard-write , depending on the needs of your app.

Feature detection

To use the Async Clipboard API while supporting all browsers, test for navigator.clipboard and fall back to earlier methods. For example, here's how you might implement pasting to include other browsers.

That's not the whole story. Before the Async Clipboard API, there were a mix of different copy and paste implementations across web browsers. In most browsers, the browser's own copy and paste can be triggered using document.execCommand('copy') and document.execCommand('paste') . If the text to be copied is a string not present in the DOM, it must be injected into the DOM and selected:

You can play with the Async Clipboard API in the demos below. On Glitch you can remix the text demo or the image demo to experiment with them.

The first example demonstrates moving text on and off the clipboard.

To try the API with images, use this demo. Recall that only PNGs are supported and only in a few browsers .

Related links

  • Web custom formats

Acknowledgements

The Asynchronous Clipboard API was implemented by Darwin Huang and Gary Kačmarčík . Darwin also provided the demo. Thanks to Kyarik and again Gary Kačmarčík for reviewing parts of this article.

Hero image by Markus Winkler on Unsplash .

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2020-07-31 UTC.

  • Skip to main content
  • Select language
  • Skip to search

Document.execCommand()

When an HTML document has been switched to designMode , the document object exposes the execCommand method which allows one to run commands to manipulate the contents of the editable region. Most commands affect the document's selection ( bold , italics , etc.), while others insert new elements (adding a link) or affect an entire line (indenting). When using contentEditable , calling execCommand() will affect the currently active editable element.

Return value

A Boolean that is false if the command is not supported or enabled.

An example of how to use it on CodePen.

Specifications

Browser compatibility.

[1] Before Firefox 41, clipboard capability needed to be enabled in the user.js preference file. See A brief guide to Mozilla preferences for more information. If the command wasn't supported or enabled, execCommand was raising an exception instead of returning false . In Firefox 41 and later, clipboard capability are enabled by default in any event handler that is able to pop-up a window (semi-trusted scripts).

  • HTMLElement.contentEditable
  • document.designMode
  • Rich-Text Editing in Mozilla
  • Scribe's "Browser Inconsistencies" documentation with bugs related to document.execCommand . ?

Document Tags and Contributors

  • NeedsBrowserCompatibility
  • NeedsExample
  • Document Object Model
  • activeElement
  • or <frameset> node of the current document, or null if no such element exists."> body
  • characterSet
  • childElementCount
  • contentType
  • element whose script is currently being processed."> currentScript
  • defaultView
  • element for HTML documents)."> documentElement
  • documentURI
  • documentURIObject
  • firstElementChild
  • elements within the current document."> forms
  • fullscreenElement
  • elements which contain the document have their allowfullscreen attribute set."> fullscreenEnabled
  • element of the current document. If there are more than one <head> elements, the first one is returned."> head
  • element of the current document."> height
  • implementation
  • lastElementChild
  • lastModified
  • lastStyleSheetSet
  • elements and <a> elements in a document with a value for the href attribute."> links
  • mozSyntheticDocument
  •  element  finishes executing its script. Does not fire if the element is added dynamically, eg with appendChild()."> onafterscriptexecute
  • onanimationcancel
  • onanimationend
  • onanimationiteration
  •  element declared in an HTML document is about to start executing. Does not fire if the element is added dynamically, eg with appendChild()."> onbeforescriptexecute
  • oncontextmenu
  • onfullscreenchange
  • onfullscreenerror
  • ongotpointercapture
  • element value changes."> oninput
  • element, etc., which fires when the resource has loaded."> onload
  • onloadstart
  • onlostpointercapture
  • onmousedown
  • onmousemove
  • onmouseover
  • of each page when the browser switches between online and offline mode. Additionally, the events bubble up from document.body, to document, ending at window. Both events are non-cancellable (you can't prevent the user from coming online, or going offline)."> ononline
  • onpointercancel
  • onpointerdown
  • onpointerenter
  • onpointerleave
  • onpointermove
  • onpointerout
  • onpointerover
  • onpointerup
  • onselectionchange
  • onselectstart
  • ontouchcancel
  • ontouchmove
  • ontouchstart
  • ontransitioncancel
  • ontransitionend
  • elements in the current document."> plugins
  • pointerLockElement
  • preferredStyleSheetSet
  • elements in the document. The returned object is an HTMLCollection."> scripts
  • scrollingElement
  • selectedStyleSheetSet
  • styleSheets
  • styleSheetSets
  • tooltipNode
  • visibilityState
  • element of the current document in pixels."> width
  • xmlEncoding
  • ) or "1.0" if the declaration is absent.'> xmlVersion
  • adoptNode()
  • caretPositionFromPoint()
  • caretRangeFromPoint()
  • createAttribute()
  • createCDATASection()
  • createComment()
  • createDocumentFragment()
  • createElement()
  • createElementNS()
  • createEntityReference()
  • createEvent()
  • createExpression()
  • createNodeIterator()
  • createNSResolver()
  • createProcessingInstruction()
  • createRange()
  • createTextNode()
  • createTouch()
  • createTouchList()
  • createTreeWalker()
  • elementFromPoint()
  • enableStyleSheetsForSet()
  • execCommand()
  • exitFullscreen()
  • exitPointerLock()
  • getAnimations()
  • getBoxObjectFor()
  • getElementById()
  • getElementsByClassName()
  • getElementsByName()
  • getElementsByTagName()
  • getElementsByTagNameNS()
  • getSelection()
  • importNode()
  • loadOverlay()
  • mozSetImageElement()
  • queryCommandEnabled()
  • queryCommandSupported()
  • querySelector()
  • querySelectorAll()
  • registerElement()
  • releaseCapture()
  • EventTarget
  • CDATASection
  • CSSPrimitiveValue
  • CSSValueList
  • CharacterData
  • CustomEvent
  • DOMConfiguration
  • DOMErrorHandler
  • DOMException
  • DOMImplementation
  • DOMImplementationList
  • DOMImplementationRegistry
  • DOMImplementationSource
  • DOMTimeStamp
  • DOMTokenList
  • DOMUserData
  • DocumentFragment
  • DocumentType
  • ElementTraversal
  • EntityReference
  • HTMLCollection
  • MutationObserver
  • NodeIterator
  • NonDocumentTypeChildNode
  • ProcessingInstruction
  • PromiseResolver
  • TextDecoder
  • TextEncoder
  • UserDataHandler
  • XMLDocument
  • Skip to main content
  • Select language
  • Skip to search
  • Sign in Github

Specifications

Browser compatibility.

When an HTML document has been switched to designMode , its document object exposes an execCommand method to run commands that manipulate the current editable region, such as form inputs or contentEditable elements.

Most commands affect the document's selection (bold, italics, etc.), while others insert new elements (adding a link), or affect an entire line (indenting). When using contentEditable , execCommand() affects the currently active editable element.

Return value

A Boolean that is false if the command is unsupported or disabled.

Note : Only returns true if part of a user interaction. Don't try using the return value to verify browser support before calling a command.

An example of how to use it on CodePen.

  • HTMLElement.contentEditable
  • document.designMode
  • Rich-Text Editing in Mozilla
  • Scribe's "Browser Inconsistencies" documentation with bugs related to document.execCommand .

Document Tags and Contributors

  • NeedsExample
  • Document Object Model
  • or node of the current document, or null if no such element exists."> body
  • characterSet
  • childElementCount
  • contentType
  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt
  • Chrome for Developers

Cut and copy commands

IE10 and above added support for the 'cut' and 'copy' commands through the Document.execCommand() method. As of Chrome version 43, these commands are also supported in Chrome.

Any text selected in the browser when one of these commands is executed will be cut or copied to the user's clipboard. This lets you offer the user a simple way to select a portion of text and copy it to the clipboard.

This becomes extremely useful when you combine it with the Selection API to programmatically select text to determine what is copied to the clipboard, which we'll be looking at in more detail later on in this article.

Simple Example

For example's sake, let's add a button which copies an email address to the user's clipboard.

We add the email address in our HTML with a button to initiate the copying when it's clicked:

Then in our JavaScript, we want to add a click event handler to our button in which we select the email address text from the js-emaillink anchor, execute a copy command so that the email address is in the user's clipboard and then we deselect the email address so the user doesn't see the selection occur.

What we are doing here is using a method of the Selection API , window.getSelection() to programmatically set the 'selection' of text to the anchor, which is the text we want to copy to the user's clipboard. After calling document.execCommand() we can remove the selection by calling window.getSelection().removeAllRanges() . If you wanted to confirm everything worked as expected you can examine the response of document.execCommand(); it returns false if the command is not supported or enabled. We wrap execCommand() in a try and catch since the 'cut' and 'copy' commands can throw an error in a few scenarios.

The 'cut' command can be used for text fields where you want to remove the text content and make it accessible via the clipboard.

Using a textarea and a button in our HTML:

We can do the following to cut the content:

queryCommandSupported and queryCommandEnabled

Ahead of calling document.execCommand() , you should ensure that this API is supported using the document.queryCommandSupported() method. In our example above we could set the button disabled state based on support like so:

The difference between document.queryCommandSupported() and document.queryCommandEnabled() is that cut and copy could be supported by a browser, but if no text is currently selected, they won't be enabled. This is useful in scenarios where you aren't setting the selection of text programmatically and want to ensure the command will do as expected, otherwise present a message to the user.

Browser Support

IE 10+, Chrome 43+, Firefox 41+, and Opera 29+ support these commands.

Safari does not support these commands.

  • Calling queryCommandSupported() from devtools will always return false .
  • At the moment cut only works when you programmatically select text .

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2015-04-14 UTC.

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Copy text using document.execcommand(copy) working only in desktop not in IOS

copy clipboard also not working in iOS,i need with format and style appled selected text in javascript or angular

Posted on Feb 1, 2023 7:08 PM

Similar questions

  • highlight to copy When I click and drag over txt to copy, the forst word is highlighted in yellow and defined. How do you copy to paste text? 160 2
  • How do I select all text to copy to clipboard? Hi. How can I select all text of a page to copy to clipboard? Long press opens a context menu with "copy" - but only the highlighted area/word with handles. And fiddling those handles across a multi miles long page - come on... I found this shortcut workaround https://ios.gadgethacks.com/how-to/get-select-all-button-for-webpages-safari-your-iphone-0384083/ I am missing something, right? 460 9
  • Clipboard help! Can i access the clipboard to insert a paragraph i copied if i had to copy and insert something else after that? 344 1

Loading page content

Page content loaded

John Galt

Feb 2, 2023 5:57 AM in response to beemeswar

Copy text using document.execcommand(copy)

I don't know that that means. To copy text in iOS, read Select, cut, copy, and paste text on iPhone - Apple Support

Defence Forum & Military Photos - DefenceTalk

  • New comments
  • Military Photos
  • Russian Military
  • Anti-Aircraft
  • SA-21/S-400 Triumf

96L6E Radar, S-400

96L6E Radar, S-400

  • Oct 18, 2010

Media information

Share this media.

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register. By continuing to use this site, you are consenting to our use of cookies. Accept Learn more…

IMAGES

  1. Document Execcommand Copy Not Working

    document.execcommand('copy') safari

  2. Vanilla JavaScript Copy Text to Clipboard with document.execCommand

    document.execcommand('copy') safari

  3. Alternative to document execCommand to copy to Clipboard in the

    document.execcommand('copy') safari

  4. Document.execCommand('copy')の代わり

    document.execcommand('copy') safari

  5. Как открыть документ в сафари

    document.execcommand('copy') safari

  6. javascript

    document.execcommand('copy') safari

VIDEO

  1. African Safari ONE

  2. Как отредактировать сайт прямо в браузере, если вы совсем не знаете HTML

  3. Copy folder structure using command prompt

  4. JavaScript DOM execCommand Method In Hindi Part 56 || Text Formatting In JavaScript

  5. Copying data from Web to Excel on a Mac

  6. How to Check iPhone Downloads

COMMENTS

  1. jquery

    document.execCommand("copy") works without any issue now in Safari. If you have a specific use case of copy command not working only in safari, one of the things that you may want to check is if your copy command is being run inside an API callback or in some other similar asynchronous fashion.

  2. Document: execCommand() method

    The execCommand method implements multiple different commands. Some of them provide access to the clipboard, while others are for editing form inputs, contenteditable elements or entire documents (when switched to design mode ). To access the clipboard, the newer Clipboard API is recommended over execCommand().

  3. How to copy text

    Using document.execCommand() Calling document.execCommand('copy') returns a boolean value that indicates whether the copy was successful. Call this command inside of a user gesture such as a click handler. This approach has limitations when compared to the Async Clipboard API. The execCommand() method only works with DOM elements.

  4. How to use Clipboard API in Safari async

    Photo by Ashim D'Silva / Unsplash. Updated: see Copy to Clipboard async using Clipboard API for a solution that works across Chrome, Safari and Firefox.. Some strings attached. Safari supports the Clipboard API for some time now, but it locks it down to only work when triggered by a direct user interaction. That sounds like a sensible precaution to keep malicious sites from messing with your ...

  5. How can I copy text to clipboard with JavaScript?

    Using Document.execCommand('copy') While support for the Clipboard API is pretty high across the board, you might need a fallback if you have to support older browsers. If that's the case, you can use Document.execCommand('copy') to do so. Here's a quick step-by-step guide: Create a <textarea> element to be appended to the document. Set its ...

  6. Using JavaScript to copy text to the clipboard

    This includes Chrome and Firefox since 2018, as well as Edge and Safari since 2020. At the time of writing, ... catch statement wraps the next section of code where the document.execCommand function is called to execute the 'copy' command. The document.execCommand function returns a Boolean object to indicate if the command was successful ...

  7. Unblocking clipboard access

    For Safari, run all asynchronous operations in a promise whose result you assign to the ClipboardItem: js new ClipboardItem({ 'foo/bar': new Promise (async ... In most browsers, the browser's own copy and paste can be triggered using document.execCommand('copy') and document.execCommand('paste'). If the text to be copied is a string not present ...

  8. Interact with the clipboard

    The difference between the two APIs is that document.execCommand this is analogous to the keyboard copy, cut, and paste actions - exchanging data between a webpage and clipboard - whereas navigator.clipboard writes and reads arbitrary data to and from the clipboard.. navigator.clipboard provide separate methods to read or write:. text content, using navigator.clipboard.readText() and ...

  9. Clipboard API

    The Clipboard API provides the ability to respond to clipboard commands (cut, copy, and paste), as well as to asynchronously read from and write to the system clipboard. Note: Use this API in preference to the deprecated document.execCommand() method for accessing the clipboard. Note: This API is not available in Web Workers (not exposed via ...

  10. Document.execCommand()

    Document. .exec. Command () When an HTML document has been switched to designMode, the document object exposes the execCommand method which allows one to run commands to manipulate the contents of the editable region. Most commands affect the document's selection ( bold, italics, etc.), while others insert new elements (adding a link) or affect ...

  11. Using execCommand (Javascript) to copy hidden text to clipboard

    Since browsers seem to behave differently when it comes to clipboard access, it took me a while to get my head around it. It's pretty similar to your solution, but the difference is to create a temporary element and fill it with the input value.That way we can keep the input's display property set to none.. There is also a workaround for IE which uses window.clipboardData.

  12. Document.execCommand()

    When an HTML document has been switched to designMode, its document object exposes an execCommand method to run commands that manipulate the current editable region, such as form inputs or contentEditable elements.. Most commands affect the document's selection (bold, italics, etc.), while others insert new elements (adding a link), or affect an entire line (indenting).

  13. Cut and copy commands

    Cut and copy commands. IE10 and above added support for the 'cut' and 'copy' commands through the Document.execCommand () method. As of Chrome version 43, these commands are also supported in Chrome. Any text selected in the browser when one of these commands is executed will be cut or copied to the user's clipboard.

  14. Copy text using document.execcommand(copy…

    Copy text using document.execcommand (copy) I don't know that that means. To copy text in iOS, read Select, cut, copy, and paste text on iPhone - Apple Support. Copy text using document.execcommand (copy) working only in desktop not in IOS. .

  15. PDF Certification of Provision of Instructional Materials 2024-25

    A: You can find a recording of the Certification 2024-25 webinar and a copy of the utilized slide deck on the State Adopted Instructional Materials web page. The webinar is linked under "Additional Supports" towards the bottom of the page. Q: Where can I find a PDF of the instructional materials listed on the online survey?

  16. javascript

    Stack Overflow Public questions & answers; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Talent Build your employer brand ; Advertising Reach developers & technologists worldwide; Labs The future of collective knowledge sharing; About the company

  17. 96L6E Radar, S-400

    96L6E Radar, S-400. First S-400 bltn, Elektrostal, Moscow. There are no comments to display.

  18. File:Flag of Elektrostal (Moscow oblast).svg

    Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.A copy of the license is included in the section entitled GNU Free Documentation License.

  19. Elektrostal Map

    Elektrostal is a city in Moscow Oblast, Russia, located 58 kilometers east of Moscow. Elektrostal has about 158,000 residents. Mapcarta, the open map.

  20. Combination of document.addEventListener and document.execCommand("copy

    Let's imagine that this copy() function is called inside of a onClick handler. Then after the onClick is triggered, then the document did register this eventListener, but it is just not triggered instantly by the document.execCommand("copy") call. It is only triggered when I after the copy() call select something manually on the screen and do ...

  21. Elektrostal to Moscow

    Drive • 1h 3m. Drive from Elektrostal to Moscow 58.6 km. RUB 450 - RUB 700. Quickest way to get there Cheapest option Distance between.

  22. document.execCommand ('copy') not working on Chrome

    35. For people reading this question in 2020, if you're having trouble with document.execCommand('copy'), you may want to try using the Clipboard API. Per Mozilla: There are two ways browser extensions can interact with the system clipboard: the Document.execCommand () method and the modern asynchronous Clipboard API.