Implementing Clipboard Functionality in WeChat Mini Programs
This tutorial demonstrates how to detect, extract, and paste content copied from WeChat into a Mini Program by using the wx.getClipboardData API, applying regular‑expression matching, and displaying a confirmation modal only when the clipboard data differs from the previously stored value.
The article introduces a practical method for retrieving and processing clipboard data in WeChat Mini Programs, targeting developers who need to detect copied links and offer a seamless paste experience.
WeChat provides two clipboard interfaces—one for setting and one for getting the system clipboard. The focus here is on the wx.getClipboardData API, whose usage rules are briefly outlined.
A minimal example shows how to call the API and log the retrieved data:
<code>wx.getClipboardData({
success (res){
console.log(res.data)
}
})</code>To extract only the needed URL from the clipboard content, a regular‑expression utility is created in the utils directory:
<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 compared with a previously stored address to avoid showing duplicate prompts.
The core logic resides in the page's onShow handler, which obtains clipboard data, runs the regex matcher, and conditionally displays a modal dialog using wx.showModal :
<code>onShow: function (res) {
let that = this;
wx.getClipboardData({
success: function (res) {
// Match address
let result = util.handleUrl(res.data);
// If the address is the same, do not show the 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) {
} else {
that.setData({
prase_address: result,
})
}
},
})
},
fail: function (res) { },
complete: function (res) { },
})
},</code>This complete example equips newcomers to Mini Program development with a ready‑to‑use pattern for clipboard detection, URL extraction, and user confirmation.
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.