Implementing Clipboard Functionality in WeChat Mini Programs
This article guides developers through implementing clipboard detection and paste functionality in WeChat mini programs, covering the use of wx.getClipboardData, regex URL extraction, conditional modal prompts, and provides complete sample code for integration.
The tutorial explains how to detect content copied from WeChat, extract the desired URL using regular expressions, and paste it into a mini‑program.
Key steps include:
Detecting the clipboard content copied from WeChat.
Using a regular expression to match the required URL.
The WeChat Mini Program provides two interfaces for clipboard operations; the article focuses on the retrieval interface wx.getClipboardData . The usage rules of this API are shown in the documentation screenshot.
Basic usage example:
<code>wx.getClipboardData({
success (res) {
console.log(res.data)
}
})
</code>For URL extraction, a utility module is created (e.g., utils/clipboard.js ) with the following regex handling code:
<code>var t = {};
t.handleUrl = function(t) {
var e = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g;
return !!(t = t.match(e)) && t[0];
};
module.exports = t;
</code>The utility is imported where needed, and the extracted URL is passed to a modal dialog. If the detected URL matches the previously stored one, the dialog is suppressed; otherwise, wx.showModal displays a prompt asking the user to paste the link.
Full integration code (excerpt):
<code>onShow: function (res) {
let that = this;
wx.getClipboardData({
success: function (res) {
// Match address
let result = util.handleUrl(res.data);
// If address is the same, do not show modal
if (result == that.data.prase_address) {
return;
}
wx.showModal({
title: '检测到视频链接,是否粘贴?',
content: result,
showCancel: true,
cancelText: "取消",
cancelColor: '#ff9900',
confirmText: "粘贴",
confirmColor: '#ff9900',
success: function (res) {
if (res.cancel) {
// user cancelled
} else {
that.setData({
prase_address: result,
})
}
},
fail: function (res) {},
complete: function (res) {}
})
},
fail: function (res) {},
complete: function (res) {}
})
},
</code>By following these steps, developers can seamlessly detect and paste URLs copied from WeChat into their mini‑programs, improving user experience.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.