uniapp H5 頁面的復(fù)制功能 三種方式 建議使用第三種

使用場景:小城跳轉(zhuǎn)到H5頁面寿桨,由于uniapp官網(wǎng)提供的uni.setClipboardData?不支持H5甘邀,但是在微信開發(fā)者工具上面是好用的练俐,而打包在手機上無效念秧。

1.嘗試方式一:

嘗試在網(wǎng)上搜索找了很多種方案激蹲,但都是無效的。如下方案看上去很絲滑的解決了問題叁温,但是在手機上回一直走 不支持復(fù)制那里,果斷放棄核畴∠サ可能是有的用戶好用吧,可能是場景不同谤草,這個方法沒有解決我的問題跟束,于是繼續(xù)探索。

2.嘗試方法二:

解決 報錯? ? ? [system] APIsetClipboardDatais not yet implemented

復(fù)制以下代碼 新建文件命名為 clipboard.js

//#ifdef H5/** clipboard.js v2.0.4**/!function(t,e){try{window.ClipboardJS=e();}catch(e){};"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ClipboardJS=e():t.ClipboardJS=e()}(this,function(){return function(n){var o={};function r(t){if(o[t])return o[t].exports;var e=o[t]={i:t,l:!1,exports:{}};return n[t].call(e.exports,e,e.exports,r),e.l=!0,e.exports} return r.m=n,r.c=o,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)}([function(t,e,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=function(){function o(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}} return function(t,e,n){return e&&o(t.prototype,e),n&&o(t,n),t}}(),a=o(n(1)),c=o(n(3)),u=o(n(4));function o(t){return t&&t.__esModule?t:{default:t}} var l=function(t){function o(t,e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,o);var n=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(o.__proto__||Object.getPrototypeOf(o)).call(this));return n.resolveOptions(e),n.listenClick(t),n} return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(o,c.default),i(o,[{key:"resolveOptions",value:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof t.action?t.action:this.defaultAction,this.target="function"==typeof t.target?t.target:this.defaultTarget,this.text="function"==typeof t.text?t.text:this.defaultText,this.container="object"===r(t.container)?t.container:document.body}},{key:"listenClick",value:function(t){var e=this;this.listener=(0,u.default)(t,"click",function(t){return e.onClick(t)})}},{key:"onClick",value:function(t){var e=t.delegateTarget||t.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new a.default({action:this.action(e),target:this.target(e),text:this.text(e),container:this.container,trigger:e,emitter:this})}},{key:"defaultAction",value:function(t){return s("action",t)||'copy'}},{key:"defaultTarget",value:function(t){var e=s("target",t);if(e){return document.querySelector(e)}}},{key:"defaultText",value:function(t){return s("text",t)||this.text}},{key:"destroy",value:function(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:["copy","cut"],e="string"==typeof t?[t]:t,n=!!document.queryCommandSupported;return e.forEach(function(t){n=n&&!!document.queryCommandSupported(t)}),n}}]),o}();function s(t,e){var n="data-clipboard-"+t;let isFun=e&&typeof e.hasAttribute==='function';if(isFun&&e.hasAttribute(n)){return e.getAttribute(n)}} t.exports=l},function(t,e,n){"use strict";var o,r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=function(){function o(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}} return function(t,e,n){return e&&o(t.prototype,e),n&&o(t,n),t}}(),a=n(2),c=(o=a)&&o.__esModule?o:{default:o};var u=function(){function e(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),this.resolveOptions(t),this.initSelection()} return i(e,[{key:"resolveOptions",value:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};this.action=t.action,this.container=t.container,this.emitter=t.emitter,this.target=t.target,this.text=t.text,this.trigger=t.trigger,this.selectedText=""}},{key:"initSelection",value:function(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function(){var t=this,e="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return t.removeFake()},this.fakeHandler=this.container.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[e?"right":"left"]="-9999px";var n=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=n+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,this.container.appendChild(this.fakeElem),this.selectedText=(0,c.default)(this.fakeElem),this.copyText()}},{key:"removeFake",value:function(){this.fakeHandler&&(this.container.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(this.container.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function(){this.selectedText=(0,c.default)(this.target),this.copyText()}},{key:"copyText",value:function(){var e=void 0;try{e=document.execCommand(this.action)}catch(t){e=!1} this.handleResult(e)}},{key:"handleResult",value:function(t){this.emitter.emit(t?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function(){this.trigger&&this.trigger.focus(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function(){this.removeFake()}},{key:"action",set:function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=t,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function(){return this._action}},{key:"target",set:function(t){if(void 0!==t){if(!t||"object"!==(void 0===t?"undefined":r(t))||1!==t.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&t.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(t.hasAttribute("readonly")||t.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=t}},get:function(){return this._target}}]),e}();t.exports=u},function(t,e){t.exports=function(t){var e;if("SELECT"===t.nodeName)t.focus(),e=t.value;else if("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName){var n=t.hasAttribute("readonly");n||t.setAttribute("readonly",""),t.select(),t.setSelectionRange(0,t.value.length),n||t.removeAttribute("readonly"),e=t.value}else{t.hasAttribute("contenteditable")&&t.focus();var o=window.getSelection(),r=document.createRange();r.selectNodeContents(t),o.removeAllRanges(),o.addRange(r),e=o.toString()} return e}},function(t,e){function n(){} n.prototype={on:function(t,e,n){var o=this.e||(this.e={});return(o[t]||(o[t]=[])).push({fn:e,ctx:n}),this},once:function(t,e,n){var o=this;function r(){o.off(t,r),e.apply(n,arguments)} return r._=e,this.on(t,r,n)},emit:function(t){for(var e=[].slice.call(arguments,1),n=((this.e||(this.e={}))[t]||[]).slice(),o=0,r=n.length;o<r;o++)n[o].fn.apply(n[o].ctx,e);return this},off:function(t,e){var n=this.e||(this.e={}),o=n[t],r=[];if(o&&e)for(var i=0,a=o.length;i<a;i++)o[i].fn!==e&&o[i].fn._!==e&&r.push(o[i]);return r.length?n[t]=r:delete n[t],this}},t.exports=n},function(t,e,n){var d=n(5),h=n(6);t.exports=function(t,e,n){if(!t&&!e&&!n)throw new Error("Missing required arguments");if(!d.string(e))throw new TypeError("Second argument must be a String");if(!d.fn(n))throw new TypeError("Third argument must be a Function");if(d.node(t))return s=e,f=n,(l=t).addEventListener(s,f),{destroy:function(){l.removeEventListener(s,f)}};if(d.nodeList(t))return a=t,c=e,u=n,Array.prototype.forEach.call(a,function(t){t.addEventListener(c,u)}),{destroy:function(){Array.prototype.forEach.call(a,function(t){t.removeEventListener(c,u)})}};if(d.string(t))return o=t,r=e,i=n,h(document.body,o,r,i);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList");var o,r,i,a,c,u,l,s,f}},function(t,n){n.node=function(t){return void 0!==t&&t instanceof HTMLElement&&1===t.nodeType},n.nodeList=function(t){var e=Object.prototype.toString.call(t);return void 0!==t&&("[object NodeList]"===e||"[object HTMLCollection]"===e)&&"length"in t&&(0===t.length||n.node(t[0]))},n.string=function(t){return"string"==typeof t||t instanceof String},n.fn=function(t){return"[object Function]"===Object.prototype.toString.call(t)}},function(t,e,n){var a=n(7);function i(t,e,n,o,r){var i=function(e,n,t,o){return function(t){t.delegateTarget=a(t.target,n),t.delegateTarget&&o.call(e,t)}}.apply(this,arguments);return t.addEventListener(n,i,r),{destroy:function(){t.removeEventListener(n,i,r)}}} t.exports=function(t,e,n,o,r){return"function"==typeof t.addEventListener?i.apply(null,arguments):"function"==typeof n?i.bind(null,document).apply(null,arguments):("string"==typeof t&&(t=document.querySelectorAll(t)),Array.prototype.map.call(t,function(t){return i(t,e,n,o,r)}))}},function(t,e){if("undefined"!=typeof Element&&!Element.prototype.matches){var n=Element.prototype;n.matches=n.matchesSelector||n.mozMatchesSelector||n.msMatchesSelector||n.oMatchesSelector||n.webkitMatchesSelector} t.exports=function(t,e){for(;t&&9!==t.nodeType;){if("function"==typeof t.matches&&t.matches(e))return t;t=t.parentNode}}}])});let Types={isFunction:function(obj){var type=Object.prototype.toString.call(obj) return type=='[object Function]'},isObject:function(obj){var type=Object.prototype.toString.call(obj) return type=='[object Object]'},isString:function(obj){var type=Object.prototype.toString.call(obj) return type=='[object String]'}}uni.setClipboardData=function(options){let emptyFun=function(){} let config={data:null,event:null,success:emptyFun,fail:emptyFun,complete:emptyFun} if(options&&Types.isObject(options)){config=Object.assign({},config,options)} if(options&&Types.isString(options)){config=Object.assign({},config,{data:options})} let data=config.data let success=config.success||emptyFun let fail=config.fail||emptyFun let complete=config.complete||emptyFun let e=config.event||window.event||{} let cb=new ClipboardJS('.null',{text:()=>data}) cb.on('success',function(res){ window.__clipboard__=data; success&&Types.isFunction(success)&&success({data:res.text}) complete&&Types.isFunction(complete)&&complete() cb.off('error') cb.off('success') cb.destroy()}) cb.on('error',function(err){fail&&Types.isFunction(fail)&&fail(err) complete&&Types.isFunction(complete)&&complete() cb.off('error') cb.off('success') cb.destroy()}) cb.onClick(e)};uni.getClipboardData=function(options){let emptyFun=function(){} let config={data:null,event:null,success:emptyFun,fail:emptyFun,complete:emptyFun} if(options&&Types.isObject(options)){config=Object.assign({},config,options)} let success=config.success||emptyFun let fail=config.fail||emptyFun let complete=config.complete||emptyFun if(window.__clipboard__!==undefined){success&&Types.isFunction(success)&&success({data:window.__clipboard__})}else{fail&&Types.isFunction(fail)&&fail({data:null})} complete&&Types.isFunction(complete)&&complete()};function fileDownLoad(data){var linkElement=document.createElement('a') linkElement.setAttribute('href',data.blob) linkElement.setAttribute('downLoad',data.name) linkElement.click()}uni.saveImageToPhotosAlbum=uni.saveVideoToPhotosAlbum=function(options){let emptyFun=function(){} let config={filePath:null,success:emptyFun,fail:emptyFun,complete:emptyFun} if(options&&Types.isObject(options)){config=Object.assign({},config,options)} if(options&&Types.isString(options)){config=Object.assign({},config,{filePath:options})} let filePath=config.filePath let success=config.success||emptyFun let fail=config.fail||emptyFun let complete=config.complete||emptyFun if(!filePath){fail&&Types.isFunction(fail)&&fail({msg:'no File'}) complete&&Types.isFunction(complete)&&complete() return} let names=filePath.split('/') let name=names[names.length-1] uni.downloadFile({url:filePath,success:function(res){let tempFilePath=res.tempFilePath fileDownLoad({name:name,blob:tempFilePath}) success&&Types.isFunction(success)&&success({filePath:filePath})},fail:function(err){fail&&Types.isFunction(fail)&&fail({msg:err})},complete:function(){complete&&Types.isFunction(complete)&&complete()}})}//#endif

然后 引用過來

import clipboardfrom "./xx/clipboard.js"

就可以直接使用了丑孩,使用的時候 會走如上的js方法冀宴,最后還是無效∥卵В可能對于某些場景會有效略贮,不然網(wǎng)上不會有這么多貼出這個方案的。

3.嘗試方式三(最終解決)

npm install clipboard --save? //項目中安裝clipboard

import Clipboard from 'clipboard';


然后頁面當中引用
import { handleClipboard? } from "../components/clipboard.js";

然后使用

// #ifdef H5 handleClipboard(re.data, () => { uni.showToast({ title: '已復(fù)制', duration: 2000, icon: 'none' }); this.$u.route({ url: 'pages/video/pages/downWay?images=' + this.images }) }, () => { uni.showToast({ title: ' 暫不支持 ', duration: 2000, icon: 'none' }); }) // #endif


最終反復(fù)測試好用U提L友印!轧拄!? 要根據(jù)自己的實際情況來使用揽祥,不能一味地照搬,我開始是用這種方式的時候 也是無效檩电,經(jīng)過無數(shù)次的改進最終國通過拄丰。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市俐末,隨后出現(xiàn)的幾起案子料按,更是在濱河造成了極大的恐慌,老刑警劉巖鹅搪,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件站绪,死亡現(xiàn)場離奇詭異,居然都是意外死亡丽柿,警方通過查閱死者的電腦和手機恢准,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進店門魂挂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人馁筐,你說我怎么就攤上這事涂召。” “怎么了敏沉?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵果正,是天一觀的道長。 經(jīng)常有香客問我盟迟,道長秋泳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任攒菠,我火速辦了婚禮迫皱,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘辖众。我一直安慰自己卓起,他們只是感情好,可當我...
    茶點故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布凹炸。 她就那樣靜靜地躺著戏阅,像睡著了一般。 火紅的嫁衣襯著肌膚如雪啤它。 梳的紋絲不亂的頭發(fā)上奕筐,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天,我揣著相機與錄音变骡,去河邊找鬼救欧。 笑死,一個胖子當著我的面吹牛锣光,可吹牛的內(nèi)容都是我干的笆怠。 我是一名探鬼主播,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼誊爹,長吁一口氣:“原來是場噩夢啊……” “哼蹬刷!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起频丘,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤办成,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后搂漠,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體迂卢,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了而克。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片靶壮。...
    茶點故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖员萍,靈堂內(nèi)的尸體忽然破棺而出腾降,到底是詐尸還是另有隱情,我是刑警寧澤碎绎,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布螃壤,位于F島的核電站,受9級特大地震影響筋帖,放射性物質(zhì)發(fā)生泄漏奸晴。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一日麸、第九天 我趴在偏房一處隱蔽的房頂上張望蚁滋。 院中可真熱鬧,春花似錦赘淮、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至副女,卻和暖如春蛤高,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背碑幅。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工戴陡, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人沟涨。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓恤批,卻偏偏與公主長得像,于是被迫代替她去往敵國和親裹赴。 傳聞我的和親對象是個殘疾皇子喜庞,可洞房花燭夜當晚...
    茶點故事閱讀 44,969評論 2 355