From d0f301c3578a1e6f69f86940e4a92ed93620178f Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Fri, 20 Dec 2024 14:19:23 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E9=83=A8=E5=88=86?= =?UTF-8?q?=E5=AE=89=E5=8D=93=E6=9C=BA=E6=8E=A5=E6=94=B6=E4=B8=8D=E5=88=B0?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/mpx-webview/H5/webviewbridge.min.js | 2 +- .../dist/webviewbridge.esm.browser.js | 67 ++++++++++++------- .../dist/webviewbridge.esm.browser.min.js | 2 +- .../webview-bridge/dist/webviewbridge.esm.js | 61 ++++++++++------- packages/webview-bridge/dist/webviewbridge.js | 61 ++++++++++------- .../webview-bridge/dist/webviewbridge.min.js | 2 +- packages/webview-bridge/src/index.js | 67 ++++++++++++------- 7 files changed, 163 insertions(+), 99 deletions(-) diff --git a/examples/mpx-webview/H5/webviewbridge.min.js b/examples/mpx-webview/H5/webviewbridge.min.js index 7ac85a8e78..850fb03c1a 100644 --- a/examples/mpx-webview/H5/webviewbridge.min.js +++ b/examples/mpx-webview/H5/webviewbridge.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -var e,o;e=this,o=function(){"use strict";var e,o,a,t,n=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(a=location.href,(t=/mpx_webview_id=(\d+)/g.exec(a))&&t[1]&&(o=+t[1]),o),s={},d=navigator.userAgent;d.indexOf("AlipayClient")>-1&&d.indexOf("MiniProgram")>-1?i="my":d.toLowerCase().indexOf("miniprogram")>-1?i=d.indexOf("QQ")>-1?"qq":"wx":d.indexOf("swan/")>-1?i="swan":d.indexOf("toutiao")>-1?i="tt":(i="web",window.addEventListener("message",(function(e){var o=e.data,a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}var t=a,n=t.callbackId,i=t.error,r=t.result;void 0!==n&&s[n]&&(i?s[n](i):s[n](null,r),delete s[n])}),!1));var g=!1;function w(o){g?o():e.then((function(){g=!0,o()}))}var p={config:function(e){"wx"===i?w((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function l(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),t=1;t1&&void 0!==arguments[1]?arguments[1]:{},a=o.time,t=void 0===a?5e3:a,n=o.crossOrigin,i=void 0!==n&&n;function r(){return new Promise((function(o,a){var t=document.createElement("script");t.type="text/javascript",t.async="async",i&&(t.crossOrigin="anonymous"),t.onload=t.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),t.onload=t.onreadystatechange=null)},t.onerror=function(){a(new Error("load ".concat(e," error"))),t.onerror=null},t.src=e,document.getElementsByTagName("head")[0].appendChild(t)}))}function c(){return new Promise((function(o,a){setTimeout((function(){a(new Error("load ".concat(e," timeout")))}),t)}))}return Promise.race([r(),c()])}(n[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),m(),p},"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e=e||self).mpx=o(); \ No newline at end of file +var e,a;e=this,a=function(){"use strict";var e,a,o,t,n=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(o=location.href,(t=/mpx_webview_id=(\d+)/g.exec(o))&&t[1]&&(a=+t[1]),a),s={},d=function(e){var a=e.data,o=a;try{"string"==typeof a&&(o=JSON.parse(a))}catch(e){}var t=o,n=t.callbackId,i=t.error,r=t.result;void 0!==n&&s[n]&&(i?s[n](i):s[n](null,r),delete s[n])},g=navigator.userAgent;g.indexOf("AlipayClient")>-1&&g.indexOf("MiniProgram")>-1?i="my":g.toLowerCase().indexOf("miniprogram")>-1?i=g.indexOf("QQ")>-1?"qq":"wx":g.indexOf("swan/")>-1?i="swan":g.indexOf("toutiao")>-1&&(i="tt"),window.ReactNativeWebView?(i="rn",g.toLowerCase().indexOf("ios")>-1?window.addEventListener("message",d,!1):document.addEventListener("message",d,!1)):(i="web",window.addEventListener("message",d,!1));var w=!1;function p(a){w?a():e.then((function(){w=!0,a()}))}var l={config:function(e){"wx"===i?p((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function m(e){for(var a=arguments.length,o=new Array(a>1?a-1:0),t=1;t1&&void 0!==arguments[1]?arguments[1]:{},o=a.time,t=void 0===o?5e3:o,n=a.crossOrigin,i=void 0!==n&&n;function r(){return new Promise((function(a,o){var t=document.createElement("script");t.type="text/javascript",t.async="async",i&&(t.crossOrigin="anonymous"),t.onload=t.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(a(),t.onload=t.onreadystatechange=null)},t.onerror=function(){o(new Error("load ".concat(e," error"))),t.onerror=null},t.src=e,document.getElementsByTagName("head")[0].appendChild(t)}))}function c(){return new Promise((function(a,o){setTimeout((function(){o(new Error("load ".concat(e," timeout")))}),t)}))}return Promise.race([r(),c()])}(n[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),v(),l},"object"==typeof exports&&"undefined"!=typeof module?module.exports=a():"function"==typeof define&&define.amd?define(a):(e=e||self).mpx=a(); \ No newline at end of file diff --git a/packages/webview-bridge/dist/webviewbridge.esm.browser.js b/packages/webview-bridge/dist/webviewbridge.esm.browser.js index e8b97d2f10..a04123e05a 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.browser.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.browser.js @@ -75,6 +75,27 @@ let env = null; let callbackId = 0; const clientUid = getMpxWebViewId(); const callbacks = {}; +const eventListener = (event) => { + // 接收web-view的回调 + const data = event.data; + let msgData = data; + try { + if (typeof data === 'string') { + msgData = JSON.parse(data); + } + } catch (e) { + } + const { callbackId, error, result } = msgData; + if (callbackId !== undefined && callbacks[callbackId]) { + if (error) { + callbacks[callbackId](error); + } else { + callbacks[callbackId](null, result); + } + delete callbacks[callbackId]; + } +}; + // 环境判断逻辑 const systemUA = navigator.userAgent; if (systemUA.indexOf('AlipayClient') > -1 && systemUA.indexOf('MiniProgram') > -1) { @@ -85,32 +106,20 @@ if (systemUA.indexOf('AlipayClient') > -1 && systemUA.indexOf('MiniProgram') > - env = 'swan'; } else if (systemUA.indexOf('toutiao') > -1) { env = 'tt'; +} if (window.ReactNativeWebView) { + env = 'rn'; + if (systemUA.toLowerCase().indexOf('ios') > -1) { + window.addEventListener('message', eventListener, false); + } else { + document.addEventListener('message', eventListener, false); // 安卓机接收消息 + } } else { env = 'web'; - window.addEventListener('message', (event) => { - // 接收web-view的回调 - const data = event.data; - let msgData = data; - try { - if (typeof data === 'string') { - msgData = JSON.parse(data); - } - } catch (e) { - } - const { callbackId, error, result } = msgData; - if (callbackId !== undefined && callbacks[callbackId]) { - if (error) { - callbacks[callbackId](error); - } else { - callbacks[callbackId](null, result); - } - delete callbacks[callbackId]; - } - }, false); + window.addEventListener('message', eventListener, false); } const initWebviewBridge = () => { - sdkReady = env !== 'web' ? SDK_URL_MAP[env].url ? loadScript(SDK_URL_MAP[env].url) : Promise.reject(new Error('未找到对应的sdk')) : Promise.resolve(); + sdkReady = (env !== 'web' && env !== 'rn') ? SDK_URL_MAP[env].url ? loadScript(SDK_URL_MAP[env].url) : Promise.reject(new Error('未找到对应的sdk')) : Promise.resolve(); getWebviewApi(); }; @@ -145,7 +154,7 @@ function postMessage (type, ...extraData) { type = extraData[0]; extraData = extraData.slice(1); } - const data = extraData[0]; + const data = extraData[0] || {}; if (type !== 'getEnv') { const currentCallbackId = ++callbackId; callbacks[currentCallbackId] = (err, res) => { @@ -311,6 +320,18 @@ const getWebviewApi = () => { 'getLocation', 'invoke' ], + rn: [ + 'navigateTo', + 'navigateBack', + 'switchTab', + 'reLaunch', + 'redirectTo', + 'getEnv', + 'postMessage', + 'getLoadError', + 'getLocation', + 'invoke' + ], tt: [] }; const multiApi = multiApiMap[env] || {}; @@ -325,7 +346,7 @@ const getWebviewApi = () => { }); singleApi.forEach((item) => { webviewBridge[item] = (...args) => { - if (env === 'web') { + if (env === 'web' || env === 'rn') { postMessage(item, ...args); } else if (env === 'wx') { runWebviewApiMethod(() => { diff --git a/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js b/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js index efbeb4cfac..56d5d53f09 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.browser.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -let e;const o=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap);let a=null,t=0;const n=function(){const e=location.href,o=/mpx_webview_id=(\d+)/g.exec(e);let a;return o&&o[1]&&(a=+o[1]),a}(),i={},s=navigator.userAgent;s.indexOf("AlipayClient")>-1&&s.indexOf("MiniProgram")>-1?a="my":s.toLowerCase().indexOf("miniprogram")>-1?a=s.indexOf("QQ")>-1?"qq":"wx":s.indexOf("swan/")>-1?a="swan":s.indexOf("toutiao")>-1?a="tt":(a="web",window.addEventListener("message",e=>{const o=e.data;let a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}const{callbackId:t,error:n,result:s}=a;void 0!==t&&i[t]&&(n?i[t](n):i[t](null,s),delete i[t])},!1));let r=!1;function c(o){r?o():e.then(()=>{r=!0,o()})}const d={config(e){"wx"===a?c(()=>{window.wx&&window.wx.config(e)}):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};const g=()=>{const e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[a]||{},o={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation","invoke"],tt:[]}[a]||[];(e.api||[]).forEach(o=>{d[o]=(...t)=>{c(()=>{window[a][e.keyName][o](...t)})}}),o.forEach(e=>{d[e]=(...o)=>{"web"===a?function(e,...o){"invoke"===e&&(e=o[0],o=o.slice(1));const a=o[0];if("getEnv"!==e){const s=++t;i[s]=(e,o)=>{e?(a.fail&&a.fail(e),a.complete&&a.complete(e)):(a.success&&a.success(o),a.complete&&a.complete(o)),delete i[s]};const r={type:e,callbackId:t,args:o};void 0!==n&&(r.clientUid=n),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(r)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(r),"*")}else a({webapp:!0})}(e,...o):c("wx"===a?()=>{window[a]&&window[a].ready(()=>{window[a][e](...o)})}:()=>{window[a][e](...o)})}})};e="web"!==a?o[a].url?function(e,{time:o=5e3,crossOrigin:a=!1}={}){return Promise.race([new Promise((o,t)=>{const n=document.createElement("script");n.type="text/javascript",n.async="async",a&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){t(new Error(`load ${e} error`)),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}),new Promise((a,t)=>{setTimeout(()=>{t(new Error(`load ${e} timeout`))},o)})])}(o[a].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),g();export default d; \ No newline at end of file +let e;const o=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap);let a=null,t=0;const n=function(){const e=location.href,o=/mpx_webview_id=(\d+)/g.exec(e);let a;return o&&o[1]&&(a=+o[1]),a}(),i={},s=e=>{const o=e.data;let a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}const{callbackId:t,error:n,result:s}=a;void 0!==t&&i[t]&&(n?i[t](n):i[t](null,s),delete i[t])},r=navigator.userAgent;r.indexOf("AlipayClient")>-1&&r.indexOf("MiniProgram")>-1?a="my":r.toLowerCase().indexOf("miniprogram")>-1?a=r.indexOf("QQ")>-1?"qq":"wx":r.indexOf("swan/")>-1?a="swan":r.indexOf("toutiao")>-1&&(a="tt"),window.ReactNativeWebView?(a="rn",r.toLowerCase().indexOf("ios")>-1?window.addEventListener("message",s,!1):document.addEventListener("message",s,!1)):(a="web",window.addEventListener("message",s,!1));let c=!1;function d(o){c?o():e.then(()=>{c=!0,o()})}const g={config(e){"wx"===a?d(()=>{window.wx&&window.wx.config(e)}):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};const w=()=>{const e={wx:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","postMessage","getEnv"]},tt:{keyName:"miniProgram",api:["redirectTo","navigateTo","switchTab","reLaunch","navigateBack","setSwipeBackModeSync","postMessage","getEnv","checkJsApi","chooseImage","compressImage","previewImage","uploadFile","getNetworkType","openLocation","getLocation"]},swan:{keyName:"webView",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]},qq:{keyName:"miniProgram",api:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage"]}}[a]||{},o={wx:["checkJSApi","chooseImage","previewImage","uploadImage","downloadImage","getLocalImgData","startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice","onVoicePlayEnd","uploadVoice","downloadVoice","translateVoice","getNetworkType","openLocation","getLocation","startSearchBeacons","stopSearchBeacons","onSearchBeacons","scanQRCode","chooseCard","addCard","openCard"],my:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","chooseImage","previewImage","getLocation","openLocation","alert","showLoading","hideLoading","getNetworkType","startShare","tradePay","postMessage","onMessage","getEnv"],swan:["makePhoneCall","setClipboardData","getNetworkType","openLocation","getLocation","chooseLocation","chooseImage","previewImage","openShare","navigateToSmartProgram"],web:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation","invoke"],rn:["navigateTo","navigateBack","switchTab","reLaunch","redirectTo","getEnv","postMessage","getLoadError","getLocation","invoke"],tt:[]}[a]||[];(e.api||[]).forEach(o=>{g[o]=(...t)=>{d(()=>{window[a][e.keyName][o](...t)})}}),o.forEach(e=>{g[e]=(...o)=>{"web"===a||"rn"===a?function(e,...o){"invoke"===e&&(e=o[0],o=o.slice(1));const a=o[0]||{};if("getEnv"!==e){const s=++t;i[s]=(e,o)=>{e?(a.fail&&a.fail(e),a.complete&&a.complete(e)):(a.success&&a.success(o),a.complete&&a.complete(o)),delete i[s]};const r={type:e,callbackId:t,args:o};void 0!==n&&(r.clientUid=n),window.ReactNativeWebView?window.ReactNativeWebView.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(r)):window.parent.postMessage&&window.parent.postMessage(JSON.stringify(r),"*")}else a({webapp:!0})}(e,...o):d("wx"===a?()=>{window[a]&&window[a].ready(()=>{window[a][e](...o)})}:()=>{window[a][e](...o)})}})};e="web"!==a&&"rn"!==a?o[a].url?function(e,{time:o=5e3,crossOrigin:a=!1}={}){return Promise.race([new Promise((o,t)=>{const n=document.createElement("script");n.type="text/javascript",n.async="async",a&&(n.crossOrigin="anonymous"),n.onload=n.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),n.onload=n.onreadystatechange=null)},n.onerror=function(){t(new Error(`load ${e} error`)),n.onerror=null},n.src=e,document.getElementsByTagName("head")[0].appendChild(n)}),new Promise((a,t)=>{setTimeout(()=>{t(new Error(`load ${e} timeout`))},o)})])}(o[a].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),w();export default g; \ No newline at end of file diff --git a/packages/webview-bridge/dist/webviewbridge.esm.js b/packages/webview-bridge/dist/webviewbridge.esm.js index f7c3d3d28d..3c43d88e2d 100644 --- a/packages/webview-bridge/dist/webviewbridge.esm.js +++ b/packages/webview-bridge/dist/webviewbridge.esm.js @@ -75,6 +75,29 @@ var env = null; var callbackId = 0; var clientUid = getMpxWebViewId(); var callbacks = {}; +var eventListener = function eventListener(event) { + // 接收web-view的回调 + var data = event.data; + var msgData = data; + try { + if (typeof data === 'string') { + msgData = JSON.parse(data); + } + } catch (e) {} + var _msgData = msgData, + callbackId = _msgData.callbackId, + error = _msgData.error, + result = _msgData.result; + if (callbackId !== undefined && callbacks[callbackId]) { + if (error) { + callbacks[callbackId](error); + } else { + callbacks[callbackId](null, result); + } + delete callbacks[callbackId]; + } +}; + // 环境判断逻辑 var systemUA = navigator.userAgent; if (systemUA.indexOf('AlipayClient') > -1 && systemUA.indexOf('MiniProgram') > -1) { @@ -85,33 +108,20 @@ if (systemUA.indexOf('AlipayClient') > -1 && systemUA.indexOf('MiniProgram') > - env = 'swan'; } else if (systemUA.indexOf('toutiao') > -1) { env = 'tt'; +} +if (window.ReactNativeWebView) { + env = 'rn'; + if (systemUA.toLowerCase().indexOf('ios') > -1) { + window.addEventListener('message', eventListener, false); + } else { + document.addEventListener('message', eventListener, false); // 安卓机接收消息 + } } else { env = 'web'; - window.addEventListener('message', function (event) { - // 接收web-view的回调 - var data = event.data; - var msgData = data; - try { - if (typeof data === 'string') { - msgData = JSON.parse(data); - } - } catch (e) {} - var _msgData = msgData, - callbackId = _msgData.callbackId, - error = _msgData.error, - result = _msgData.result; - if (callbackId !== undefined && callbacks[callbackId]) { - if (error) { - callbacks[callbackId](error); - } else { - callbacks[callbackId](null, result); - } - delete callbacks[callbackId]; - } - }, false); + window.addEventListener('message', eventListener, false); } var initWebviewBridge = function initWebviewBridge() { - sdkReady = env !== 'web' ? SDK_URL_MAP[env].url ? loadScript(SDK_URL_MAP[env].url) : Promise.reject(new Error('未找到对应的sdk')) : Promise.resolve(); + sdkReady = env !== 'web' && env !== 'rn' ? SDK_URL_MAP[env].url ? loadScript(SDK_URL_MAP[env].url) : Promise.reject(new Error('未找到对应的sdk')) : Promise.resolve(); getWebviewApi(); }; var webviewSdkready = false; @@ -146,7 +156,7 @@ function postMessage(type) { type = extraData[0]; extraData = extraData.slice(1); } - var data = extraData[0]; + var data = extraData[0] || {}; if (type !== 'getEnv') { var currentCallbackId = ++callbackId; callbacks[currentCallbackId] = function (err, res) { @@ -202,6 +212,7 @@ var getWebviewApi = function getWebviewApi() { my: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'chooseImage', 'previewImage', 'getLocation', 'openLocation', 'alert', 'showLoading', 'hideLoading', 'getNetworkType', 'startShare', 'tradePay', 'postMessage', 'onMessage', 'getEnv'], swan: ['makePhoneCall', 'setClipboardData', 'getNetworkType', 'openLocation', 'getLocation', 'chooseLocation', 'chooseImage', 'previewImage', 'openShare', 'navigateToSmartProgram'], web: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'getLoadError', 'getLocation', 'invoke'], + rn: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'getLoadError', 'getLocation', 'invoke'], tt: [] }; var multiApi = multiApiMap[env] || {}; @@ -223,7 +234,7 @@ var getWebviewApi = function getWebviewApi() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } - if (env === 'web') { + if (env === 'web' || env === 'rn') { postMessage.apply(void 0, [item].concat(args)); } else if (env === 'wx') { runWebviewApiMethod(function () { diff --git a/packages/webview-bridge/dist/webviewbridge.js b/packages/webview-bridge/dist/webviewbridge.js index e1a097571e..6332a7eee7 100644 --- a/packages/webview-bridge/dist/webviewbridge.js +++ b/packages/webview-bridge/dist/webviewbridge.js @@ -81,6 +81,29 @@ var callbackId = 0; var clientUid = getMpxWebViewId(); var callbacks = {}; + var eventListener = function eventListener(event) { + // 接收web-view的回调 + var data = event.data; + var msgData = data; + try { + if (typeof data === 'string') { + msgData = JSON.parse(data); + } + } catch (e) {} + var _msgData = msgData, + callbackId = _msgData.callbackId, + error = _msgData.error, + result = _msgData.result; + if (callbackId !== undefined && callbacks[callbackId]) { + if (error) { + callbacks[callbackId](error); + } else { + callbacks[callbackId](null, result); + } + delete callbacks[callbackId]; + } + }; + // 环境判断逻辑 var systemUA = navigator.userAgent; if (systemUA.indexOf('AlipayClient') > -1 && systemUA.indexOf('MiniProgram') > -1) { @@ -91,33 +114,20 @@ env = 'swan'; } else if (systemUA.indexOf('toutiao') > -1) { env = 'tt'; + } + if (window.ReactNativeWebView) { + env = 'rn'; + if (systemUA.toLowerCase().indexOf('ios') > -1) { + window.addEventListener('message', eventListener, false); + } else { + document.addEventListener('message', eventListener, false); // 安卓机接收消息 + } } else { env = 'web'; - window.addEventListener('message', function (event) { - // 接收web-view的回调 - var data = event.data; - var msgData = data; - try { - if (typeof data === 'string') { - msgData = JSON.parse(data); - } - } catch (e) {} - var _msgData = msgData, - callbackId = _msgData.callbackId, - error = _msgData.error, - result = _msgData.result; - if (callbackId !== undefined && callbacks[callbackId]) { - if (error) { - callbacks[callbackId](error); - } else { - callbacks[callbackId](null, result); - } - delete callbacks[callbackId]; - } - }, false); + window.addEventListener('message', eventListener, false); } var initWebviewBridge = function initWebviewBridge() { - sdkReady = env !== 'web' ? SDK_URL_MAP[env].url ? loadScript(SDK_URL_MAP[env].url) : Promise.reject(new Error('未找到对应的sdk')) : Promise.resolve(); + sdkReady = env !== 'web' && env !== 'rn' ? SDK_URL_MAP[env].url ? loadScript(SDK_URL_MAP[env].url) : Promise.reject(new Error('未找到对应的sdk')) : Promise.resolve(); getWebviewApi(); }; var webviewSdkready = false; @@ -152,7 +162,7 @@ type = extraData[0]; extraData = extraData.slice(1); } - var data = extraData[0]; + var data = extraData[0] || {}; if (type !== 'getEnv') { var currentCallbackId = ++callbackId; callbacks[currentCallbackId] = function (err, res) { @@ -208,6 +218,7 @@ my: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'chooseImage', 'previewImage', 'getLocation', 'openLocation', 'alert', 'showLoading', 'hideLoading', 'getNetworkType', 'startShare', 'tradePay', 'postMessage', 'onMessage', 'getEnv'], swan: ['makePhoneCall', 'setClipboardData', 'getNetworkType', 'openLocation', 'getLocation', 'chooseLocation', 'chooseImage', 'previewImage', 'openShare', 'navigateToSmartProgram'], web: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'getLoadError', 'getLocation', 'invoke'], + rn: ['navigateTo', 'navigateBack', 'switchTab', 'reLaunch', 'redirectTo', 'getEnv', 'postMessage', 'getLoadError', 'getLocation', 'invoke'], tt: [] }; var multiApi = multiApiMap[env] || {}; @@ -229,7 +240,7 @@ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } - if (env === 'web') { + if (env === 'web' || env === 'rn') { postMessage.apply(void 0, [item].concat(args)); } else if (env === 'wx') { runWebviewApiMethod(function () { diff --git a/packages/webview-bridge/dist/webviewbridge.min.js b/packages/webview-bridge/dist/webviewbridge.min.js index 7ac85a8e78..850fb03c1a 100644 --- a/packages/webview-bridge/dist/webviewbridge.min.js +++ b/packages/webview-bridge/dist/webviewbridge.min.js @@ -3,4 +3,4 @@ * (c) 2024 @mpxjs team * @license Apache */ -var e,o;e=this,o=function(){"use strict";var e,o,a,t,n=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(a=location.href,(t=/mpx_webview_id=(\d+)/g.exec(a))&&t[1]&&(o=+t[1]),o),s={},d=navigator.userAgent;d.indexOf("AlipayClient")>-1&&d.indexOf("MiniProgram")>-1?i="my":d.toLowerCase().indexOf("miniprogram")>-1?i=d.indexOf("QQ")>-1?"qq":"wx":d.indexOf("swan/")>-1?i="swan":d.indexOf("toutiao")>-1?i="tt":(i="web",window.addEventListener("message",(function(e){var o=e.data,a=o;try{"string"==typeof o&&(a=JSON.parse(o))}catch(e){}var t=a,n=t.callbackId,i=t.error,r=t.result;void 0!==n&&s[n]&&(i?s[n](i):s[n](null,r),delete s[n])}),!1));var g=!1;function w(o){g?o():e.then((function(){g=!0,o()}))}var p={config:function(e){"wx"===i?w((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function l(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),t=1;t1&&void 0!==arguments[1]?arguments[1]:{},a=o.time,t=void 0===a?5e3:a,n=o.crossOrigin,i=void 0!==n&&n;function r(){return new Promise((function(o,a){var t=document.createElement("script");t.type="text/javascript",t.async="async",i&&(t.crossOrigin="anonymous"),t.onload=t.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(o(),t.onload=t.onreadystatechange=null)},t.onerror=function(){a(new Error("load ".concat(e," error"))),t.onerror=null},t.src=e,document.getElementsByTagName("head")[0].appendChild(t)}))}function c(){return new Promise((function(o,a){setTimeout((function(){a(new Error("load ".concat(e," timeout")))}),t)}))}return Promise.race([r(),c()])}(n[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),m(),p},"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e=e||self).mpx=o(); \ No newline at end of file +var e,a;e=this,a=function(){"use strict";var e,a,o,t,n=Object.assign({wx:{url:"https://res.wx.qq.com/open/js/jweixin-1.3.2.js"},qq:{url:"https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"},my:{url:"https://appx/web-view.min.js"},swan:{url:"https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.4.js"},tt:{url:"https://lf3-cdn-tos.bytegoofy.com/obj/goofy/developer/jssdk/jssdk-1.2.1.js"}},window.sdkUrlMap),i=null,r=0,c=(o=location.href,(t=/mpx_webview_id=(\d+)/g.exec(o))&&t[1]&&(a=+t[1]),a),s={},d=function(e){var a=e.data,o=a;try{"string"==typeof a&&(o=JSON.parse(a))}catch(e){}var t=o,n=t.callbackId,i=t.error,r=t.result;void 0!==n&&s[n]&&(i?s[n](i):s[n](null,r),delete s[n])},g=navigator.userAgent;g.indexOf("AlipayClient")>-1&&g.indexOf("MiniProgram")>-1?i="my":g.toLowerCase().indexOf("miniprogram")>-1?i=g.indexOf("QQ")>-1?"qq":"wx":g.indexOf("swan/")>-1?i="swan":g.indexOf("toutiao")>-1&&(i="tt"),window.ReactNativeWebView?(i="rn",g.toLowerCase().indexOf("ios")>-1?window.addEventListener("message",d,!1):document.addEventListener("message",d,!1)):(i="web",window.addEventListener("message",d,!1));var w=!1;function p(a){w?a():e.then((function(){w=!0,a()}))}var l={config:function(e){"wx"===i?p((function(){window.wx&&window.wx.config(e)})):console.warn("\u975e\u5fae\u4fe1\u73af\u5883\u4e0d\u9700\u8981\u914d\u7f6econfig")}};function m(e){for(var a=arguments.length,o=new Array(a>1?a-1:0),t=1;t1&&void 0!==arguments[1]?arguments[1]:{},o=a.time,t=void 0===o?5e3:o,n=a.crossOrigin,i=void 0!==n&&n;function r(){return new Promise((function(a,o){var t=document.createElement("script");t.type="text/javascript",t.async="async",i&&(t.crossOrigin="anonymous"),t.onload=t.onreadystatechange=function(){this.readyState&&!/^(loaded|complete)$/.test(this.readyState)||(a(),t.onload=t.onreadystatechange=null)},t.onerror=function(){o(new Error("load ".concat(e," error"))),t.onerror=null},t.src=e,document.getElementsByTagName("head")[0].appendChild(t)}))}function c(){return new Promise((function(a,o){setTimeout((function(){o(new Error("load ".concat(e," timeout")))}),t)}))}return Promise.race([r(),c()])}(n[i].url):Promise.reject(new Error("\u672a\u627e\u5230\u5bf9\u5e94\u7684sdk")):Promise.resolve(),v(),l},"object"==typeof exports&&"undefined"!=typeof module?module.exports=a():"function"==typeof define&&define.amd?define(a):(e=e||self).mpx=a(); \ No newline at end of file diff --git a/packages/webview-bridge/src/index.js b/packages/webview-bridge/src/index.js index 054b022d22..11571c1030 100644 --- a/packages/webview-bridge/src/index.js +++ b/packages/webview-bridge/src/index.js @@ -31,6 +31,27 @@ let env = null let callbackId = 0 const clientUid = getMpxWebViewId() const callbacks = {} +const eventListener = (event) => { + // 接收web-view的回调 + const data = event.data + let msgData = data + try { + if (typeof data === 'string') { + msgData = JSON.parse(data) + } + } catch (e) { + } + const { callbackId, error, result } = msgData + if (callbackId !== undefined && callbacks[callbackId]) { + if (error) { + callbacks[callbackId](error) + } else { + callbacks[callbackId](null, result) + } + delete callbacks[callbackId] + } +} + // 环境判断逻辑 const systemUA = navigator.userAgent if (systemUA.indexOf('AlipayClient') > -1 && systemUA.indexOf('MiniProgram') > -1) { @@ -41,32 +62,20 @@ if (systemUA.indexOf('AlipayClient') > -1 && systemUA.indexOf('MiniProgram') > - env = 'swan' } else if (systemUA.indexOf('toutiao') > -1) { env = 'tt' +} if (window.ReactNativeWebView) { + env = 'rn' + if (systemUA.toLowerCase().indexOf('ios') > -1) { + window.addEventListener('message', eventListener, false) + } else { + document.addEventListener('message', eventListener, false) // 安卓机接收消息 + } } else { env = 'web' - window.addEventListener('message', (event) => { - // 接收web-view的回调 - const data = event.data - let msgData = data - try { - if (typeof data === 'string') { - msgData = JSON.parse(data) - } - } catch (e) { - } - const { callbackId, error, result } = msgData - if (callbackId !== undefined && callbacks[callbackId]) { - if (error) { - callbacks[callbackId](error) - } else { - callbacks[callbackId](null, result) - } - delete callbacks[callbackId] - } - }, false) + window.addEventListener('message', eventListener, false) } const initWebviewBridge = () => { - sdkReady = env !== 'web' ? SDK_URL_MAP[env].url ? loadScript(SDK_URL_MAP[env].url) : Promise.reject(new Error('未找到对应的sdk')) : Promise.resolve() + sdkReady = (env !== 'web' && env !== 'rn') ? SDK_URL_MAP[env].url ? loadScript(SDK_URL_MAP[env].url) : Promise.reject(new Error('未找到对应的sdk')) : Promise.resolve() getWebviewApi() } @@ -101,7 +110,7 @@ function postMessage (type, ...extraData) { type = extraData[0] extraData = extraData.slice(1) } - const data = extraData[0] + const data = extraData[0] || {} if (type !== 'getEnv') { const currentCallbackId = ++callbackId callbacks[currentCallbackId] = (err, res) => { @@ -267,6 +276,18 @@ const getWebviewApi = () => { 'getLocation', 'invoke' ], + rn: [ + 'navigateTo', + 'navigateBack', + 'switchTab', + 'reLaunch', + 'redirectTo', + 'getEnv', + 'postMessage', + 'getLoadError', + 'getLocation', + 'invoke' + ], tt: [] } const multiApi = multiApiMap[env] || {} @@ -281,7 +302,7 @@ const getWebviewApi = () => { }) singleApi.forEach((item) => { webviewBridge[item] = (...args) => { - if (env === 'web') { + if (env === 'web' || env === 'rn') { postMessage(item, ...args) } else if (env === 'wx') { runWebviewApiMethod(() => { From 138b6ec1e0ce6b478704302474871e1c0bba4a0c Mon Sep 17 00:00:00 2001 From: wangcuijuan Date: Sat, 21 Dec 2024 18:32:10 +0800 Subject: [PATCH 2/2] =?UTF-8?q?bugfix=20=E5=AE=89=E5=8D=93=E4=B8=8Bactions?= =?UTF-8?q?heet=E9=80=89=E9=A1=B9=E9=9C=80=E8=A6=81=E7=82=B9=E4=B8=A4?= =?UTF-8?q?=E6=AC=A1=E8=A2=AB=E8=A7=A6=E5=8F=91=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx b/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx index e28b212dcf..b939fc907c 100644 --- a/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx +++ b/packages/api-proxy/src/platform/api/action-sheet/rnActionSheet.jsx @@ -92,7 +92,8 @@ function showActionSheet (options = {}) { } return ( - + {/* pointerEvents="none" 解决安卓下选项需要点两次被触发的问题 */} + { alertText ? {alertText} : null } { itemList.map((item, index) => selectAction(index)} style={ [styles.itemStyle, itemList.length -1 === index ? { borderBottomWidth: 6,