// schema協議簡介和使用 // 如下是演示,沒法正常運行,微信有嚴格的權限驗證,外部頁面不能隨意使用schema var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = 'weixin://dl/scan'; //iframe訪問schema var body = document.body || document.getElementsByTagName('body')[0]; body.appendChild(iframe); setTimeout(function() { body.removeChild(iframe); //銷燬iframe iframe = null; })
加上參數和callbackcss
// 若是要加上參數和callback,那麼就要這麼寫 window['_weixin_scan_callback'] = function(result) { alert(result); } // ..省略 iframe.src = 'weixin://dl/scan?k1=v1&k2=v2&callback=_weixin_scan_callback' // ..省略
schema協議的封裝html
新建invoke.js前端
(function(window) { // 跳用schema的封裝 function _invoke(action, data, callback) { // 拼裝schema協議 var schema = 'myapp://utils/' + action; // 拼接參數 schema += '?a=a'; var key; for (key in data) { if (data.hasOwnProperty(key)) { schema += '&' + key + data[key]; } } // 處理callback var callbackName = ''; if (typeof callback === 'string') { callbackName = callback; } else { callbackName = action + Date.now(); window[callbackName] = callback; } schema += '&callback=' + callbackName; // 觸發 var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = schema; //重要 var body = document.body || document.getElementsByTagName('body')[0]; body.appendChild(iframe); setTimeout(function() { body.removeChild(iframe); //銷燬iframe iframe = null; }) } // 暴露到全局變量 window.invoke = { share: function(data, callback) { _invoke('share', data, callback) }, scan: function