H5's Clipboard API can realize image and rich text copying through ClipboardItem and navigator.clipboard, but need to pay attention to compatibility and security policies. 1. Image copying requires fetching the image and turning it into the blob and creating a ClipboardItem, using navigator.clipboard.write to write to the clipboard, but it needs to be triggered by HTTPS environment and user gestures, and the support situation of different platform formats is tested. 2. It is recommended to use navigator.clipboard.writeText for rich text copying. You can also construct ClipboardItems containing text/plain and text/html types to preserve styles. 3. All replication operations must be triggered by user interaction and handle permission exceptions. If necessary, downgrade to use execCommand.
H5's Clipboard API really makes the front-end more capable of operating clipboards, especially when dealing with images and rich text. However, it also has some limitations and precautions on use. Next, I will start from the actual application scenarios and talk about how to use this API to implement some common functions.

Copy the image to the clipboard: Supported but conditional
In a mobile browser, if you want to copy an image to the clipboard, you can implement it through ClipboardItem
and ImageBitmap
, but not all browsers support it, especially some old versions or domestic shell browsers.
The basic process is as follows:

- Get image resources through
fetch
- Convert to blob
- Create
ClipboardItem
- Write to the clipboard using
navigator.clipboard.write()
Sample code snippet:
async function copyImageToClipboard(url) { const response = await fetch(url); const blob = await response.blob(); const item = new ClipboardItem({ [blob.type]: blob }); await navigator.clipboard.write([item]); }
Points to note:

- It must be in HTTPS environment to call
- Some browsers require user gestures to trigger (such as click events)
- Different platforms support different image formats, it is best to test WebP and JPEG
Rich text copying is more flexible and has better compatibility
Rich text copying is much more stable than images. You can use navigator.clipboard.writeText()
to copy plain text, or you can use execCommand('copy')
to perform compatibility in the old environment.
Modern recommended writing method:
navigator.clipboard.writeText('<p>This is rich text content</p>') .then(() => alert('Copy successfully')) .catch(err => console.error('Copy failed', err));
If you want to copy styled HTML content, you may also need to manually construct the pasteboard data structure in some editor scenarios, such as adding text/html
type content.
A slightly more complicated example:
const html = '<strong>bold text</strong>'; const text = 'bold text'; const clipboardItem = new ClipboardItem({ 'text/plain': new Blob([text], { type: 'text/plain' }), 'text/html': new Blob([html], { type: 'text/html' }) }); await navigator.clipboard.write([clipboardItem]);
The advantage of this is that you can retain the style when you paste in places where rich text pastes are supported (such as Word or rich text editor).
User interaction trigger is very important, don't forget the permission issue
Whether you are copying images or rich text, it must be triggered by the user's active behavior , such as clicking buttons, long pressing, etc. Otherwise the browser will throw an error to prevent abuse.
In addition, some browsers will pop up permission requests, and you need to handle exceptions:
try { await navigator.clipboard.writeText('content'); } catch (err) { console.error('Clipboard cannot be accessed', err); }
If you encounter an unsupported environment, you can consider downgrading to document.execCommand('copy')
. Although this method has been abandoned, it is still useful in some old projects.
Basically that's it. The Clipboard API function of H5 is very practical, but in actual development, you should pay attention to compatibility and security policies, and you cannot expect all devices to be perfectly supported.
The above is the detailed content of H5 Clipboard API for Image and Rich Text Manipulation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

inputtype="range" is used to create a slider control, allowing the user to select a value from a predefined range. 1. It is mainly suitable for scenes where values ??need to be selected intuitively, such as adjusting volume, brightness or scoring systems; 2. The basic structure includes min, max and step attributes, which set the minimum value, maximum value and step size respectively; 3. This value can be obtained and used in real time through JavaScript to improve the interactive experience; 4. It is recommended to display the current value and pay attention to accessibility and browser compatibility issues when using it.

The way to add drag and drop functionality to a web page is to use HTML5's DragandDrop API, which is natively supported without additional libraries. The specific steps are as follows: 1. Set the element draggable="true" to enable drag; 2. Listen to dragstart, dragover, drop and dragend events; 3. Set data in dragstart, block default behavior in dragover, and handle logic in drop. In addition, element movement can be achieved through appendChild and file upload can be achieved through e.dataTransfer.files. Note: preventDefault must be called

AnimatingSVGwithCSSispossibleusingkeyframesforbasicanimationsandtransitionsforinteractiveeffects.1.Use@keyframestodefineanimationstagesforpropertieslikescale,opacity,andcolor.2.ApplytheanimationtoSVGelementssuchas,,orviaCSSclasses.3.Forhoverorstate-b

WebRTC is a free, open source technology that supports real-time communication between browsers and devices. It realizes audio and video capture, encoding and point-to-point transmission through built-in API, without plug-ins. Its working principle includes: 1. The browser captures audio and video input; 2. The data is encoded and transmitted directly to another browser through a security protocol; 3. The signaling server assists in the initial connection but does not participate in media transmission; 4. The connection is established to achieve low-latency direct communication. The main application scenarios are: 1. Video conferencing (such as GoogleMeet, Jitsi); 2. Customer service voice/video chat; 3. Online games and collaborative applications; 4. IoT and real-time monitoring. Its advantages are cross-platform compatibility, no download required, default encryption and low latency, suitable for point-to-point communication

To confirm whether the browser can play a specific video format, you can follow the following steps: 1. Check the browser's official documents or CanIuse website to understand the supported formats, such as Chrome supports MP4, WebM, etc., Safari mainly supports MP4; 2. Use HTML5 tag local test to load the video file to see if it can play normally; 3. Upload files with online tools such as VideoJSTechInsights or BrowserStackLive for cross-platform detection. When testing, you need to pay attention to the impact of the encoded version, and you cannot rely solely on the file suffix name to judge compatibility.

The key to using requestAnimationFrame() to achieve smooth animation on HTMLCanvas is to understand its operating mechanism and cooperate with Canvas' drawing process. 1. requestAnimationFrame() is an API designed for animation by the browser. It can be synchronized with the screen refresh rate, avoid lag or tear, and is more efficient than setTimeout or setInterval; 2. The animation infrastructure includes preparing canvas elements, obtaining context, and defining the main loop function animate(), where the canvas is cleared and the next frame is requested for continuous redrawing; 3. To achieve dynamic effects, state variables, such as the coordinates of small balls, are updated in each frame, thereby forming

The core reason why browsers restrict the automatic playback of HTML5 videos is to improve the user experience and prevent unauthorized sound playback and resource consumption. The main strategies include: 1. When there is no user interaction, audio automatic playback is prohibited by default; 2. Allow mute automatic playback; 3. Audio videos must be played after the user clicks. The methods to achieve compatibility include: setting muted properties, mute first and then play in JS, and waiting for user interaction before playing. Browsers such as Chrome and Safari perform slightly differently on this strategy, but the overall trend is consistent. Developers can optimize the experience by first mute playback and provide an unmute button, monitoring user clicks, and handling playback exceptions. These restrictions are particularly strict on mobile devices, with the aim of avoiding unexpected traffic consumption and multiple videos

The security risks of HTML5 applications need to be paid attention to in front-end development, mainly including XSS attacks, interface security and third-party library risks. 1. Prevent XSS: Escape user input, use textContent, CSP header, input verification, avoid eval() and direct execution of JSON; 2. Protect interface: Use CSRFToken, SameSiteCookie policies, request frequency limits, and sensitive information to encrypt transmission; 3. Secure use of third-party libraries: periodic audit dependencies, use stable versions, reduce external resources, enable SRI verification, ensure that security lines have been built from the early stage of development.
