@tb-app/web-view
Version:
实现webview与淘宝小程序之间的通信
715 lines (627 loc) • 18.3 kB
JavaScript
import { subscribeOnce, publish, subscribe, unsubscribe } from '@tb-app/pub-sub';
import * as api from '@tb-app/pc-api';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
if (typeof my !== 'undefined') {
my.onMessage = function onMessage(result) {
var token = result.token, type = result.type, data = __rest(result, ["token", "type"]);
publish(token || type, data);
};
}
/**
* 只能在 web-view 端调用,使用小程序端注册的功能
* @param options
* @returns
*/
function invoke(options) {
return new Promise(function (resolve, reject) {
var token = subscribeOnce(options.type, function (_a) {
var success = _a.success, data = _a.data, error = _a.error;
if (success) {
resolve(data);
}
else {
try {
reject(JSON.parse(error));
}
catch (e) {
reject(new Error(error));
}
}
});
var message = {
type: options.type,
data: options.data,
token: token,
};
my.postMessage(message);
});
}
/**
* 只能在 web-view 端调用, 同一类消息可以注册多个事件回调
* @param type
* @param callback
*/
function listen(type, callback) {
subscribe(type, callback);
}
/**
* 只能在 web-view 端调用,用于移除对应的事件监听
* @param type
*/
function removeListen(type) {
unsubscribe(type);
}
var prefix = 'web_view_api_';
var webViewContextCache = {};
var postMessage = function (result, webViewId) {
var webViewContext = webViewContextCache[webViewId];
if (!webViewContext) {
webViewContext = my.createWebViewContext(webViewId);
if (!webViewContext) {
throw new Error("id \u4E3A " + webViewId + " \u7684webview\u7EC4\u4EF6\u4E0D\u5B58\u5728");
}
webViewContextCache[webViewId] = webViewContext;
}
webViewContext.postMessage(result);
};
/**
* 注册消息,只能在小程序端视频
* @param type 消息名称
* @param callback 回调
* @returns
*/
var registry = function (type, callback) {
subscribe(type, function (data) {
var token = data.token, webViewId = data.webViewId;
Promise.resolve()
.then(function () {
return callback(data.data);
})
.then(function (res) { return postMessage({ data: res, success: true, token: token, type: type }, webViewId); })
.catch(function (e) {
postMessage({
error: e ? e.message || e.toString() : type + " \u8C03\u7528\u51FA\u9519",
success: false,
token: token,
type: type,
}, webViewId);
});
});
};
/**
* 自动注册所有小程序api(不包含事件监听和获取上下文之类API)
*/
function autoRegistry() {
Object.keys(api).forEach(function (key) {
// 只注册不带on前缀的api
if (key.indexOf('on') !== 0) {
// @ts-ignore
registry("" + prefix + key, api[key]);
}
});
}
/**
* 触发注册的消息, 只能在小程序端的web-view组件的 onMessage 处理函数上使用
* @param param 传给消息回调的数据
* @param webViewId web-view的id
*/
var trigger = function (param, webViewId) {
var type = param.type, data = param.data, token = param.token;
publish(type, {
data: data,
webViewId: webViewId,
token: token,
});
};
function wrapInvoke(_a) {
var type = _a.type, data = _a.data;
return invoke({
type: "" + prefix + type,
data: data,
});
}
/**
* 跳转到指定 tabBar 页面,并关闭其他所有非 tabBar 页面
*/
function switchTab(options) {
return wrapInvoke({ type: 'switchTab', data: options });
}
/**
* 关闭当前所有页面,跳转到应用内的某个指定页面
*/
function reLaunch(options) {
return wrapInvoke({ type: 'reLaunch', data: options });
}
/**
* 关闭当前页面,跳转到应用内的某个指定页面
*/
function redirectTo(options) {
return wrapInvoke({ type: 'redirectTo', data: options });
}
/**
* 保留当前页面,跳转到应用内的某个指定页面
*/
function navigateTo(options) {
return wrapInvoke({ type: 'navigateTo', data: options });
}
/**
* 关闭当前页面,返回上一级或多级页面
*/
function navigateBack(options) {
return wrapInvoke({ type: 'navigateBack', data: options });
}
/**
* 跳转千牛容器打开H5页面
*/
function navigateToWebPage(options) {
return wrapInvoke({ type: 'qn.navigateToWebPage', data: options });
}
/**
* 小程序跳转到QAP
*/
function navigateToQAP(options) {
return wrapInvoke({ type: 'qn.navigateToQAP', data: options });
}
/**
* 关闭插件页面
*/
function closeQAP() {
return wrapInvoke({ type: 'qn.closeQAP' });
}
/**
* 显示 tabBar
*/
function showTabBar(options) {
return wrapInvoke({ type: 'showTabBar', data: options });
}
/**
* 隐藏 tabBar
*/
function hideTabBar(options) {
return wrapInvoke({ type: 'hideTabBar', data: options });
}
/**
* 动态设置 tabBar 某一项的内容
*/
function setTabBarItem(options) {
return wrapInvoke({ type: 'setTabBarItem', data: options });
}
/**
* 显示 tabBar 某一项的右上角的红点
*/
function showTabBarRedDot(options) {
return wrapInvoke({ type: 'showTabBarRedDot', data: options });
}
/**
* 隐藏 tabBar 某一项的右上角的红点
*/
function hideTabBarRedDot(options) {
return wrapInvoke({ type: 'hideTabBarRedDot', data: options });
}
/**
* 为 tabBar 某一项的右上角添加文本
*/
function setTabBarBadge(options) {
return wrapInvoke({ type: 'setTabBarBadge', data: options });
}
/**
* 移除 tabBar 某一项右上角的文本
*/
function removeTabBarBadge(options) {
return wrapInvoke({ type: 'removeTabBarBadge', data: options });
}
/**
* 切换左侧导航条选中项
*/
function switchTabEx(options) {
return wrapInvoke({ type: 'qn.switchTabEx', data: options });
}
/**
* 显示左侧导航栏中指定的菜单项
*/
function showTabEx(options) {
return wrapInvoke({ type: 'qn.showTabEx', data: options });
}
/**
* 隐藏左侧导航栏中指定的菜单项
*/
function hideTabEx(options) {
return wrapInvoke({ type: 'qn.hideTabEx', data: options });
}
/**
* 导航菜单显示红点
*/
function showTabBarRedDotEx(options) {
return wrapInvoke({ type: 'qn.showTabBarRedDotEx', data: options });
}
/**
* 导航菜单隐藏红点
*/
function hideTabBarRedDotEx(options) {
return wrapInvoke({ type: 'qn.hideTabBarRedDotEx', data: options });
}
/**
* 导航菜单显示提醒文字
*/
function setTabBarBadgeEx(options) {
return wrapInvoke({ type: 'qn.setTabBarBadgeEx', data: options });
}
/**
* 导航菜单移除提醒文字
*/
function removeTabBarBadgeEx(options) {
return wrapInvoke({ type: 'qn.removeTabBarBadgeEx', data: options });
}
/**
* 警告框:可以设置警告框的标题、内容、按钮文字等,暂不支持设置图片等样式
*/
function alert(options) {
return wrapInvoke({
type: 'alert',
data: options,
});
}
/**
* 确认框:弹窗样式不支持定制
*/
function confirm(options) {
return wrapInvoke({ type: 'confirm', data: options });
}
/**
* 显示一个弱提示,可选择多少秒之后消失
*/
function showToast(options) {
return wrapInvoke({ type: 'showToast', data: options });
}
/**
* 隐藏弱提示
*/
function hideToast() {
return wrapInvoke({ type: 'hideToast' });
}
/**
* 显示加载提示的过渡效果
*/
function showLoading(options) {
return wrapInvoke({ type: 'showLoading', data: options });
}
/**
* 隐藏加载提示
*/
function hideLoading(options) {
return wrapInvoke({ type: 'hideLoading', data: options });
}
/**
* 拍照或从手机相册中选择图片:请注意,淘宝小程序不支持设置sizeType字段。 另外,此API获取到的图片路径是伪路径,若要获取本地路径,需要配合my.getImageInfo 使用。
*/
function chooseImage(options) {
return wrapInvoke({ type: 'chooseImage', data: options });
}
/**
* 压缩图片
*/
function compressImage(options) {
return wrapInvoke({ type: 'compressImage', data: options });
}
/**
* 保存在线图片到手机相册
*/
function saveImage(options) {
return wrapInvoke({ type: 'saveImage', data: options });
}
/**
* 预览图片
*/
function previewImage(options) {
return wrapInvoke({ type: 'previewImage', data: options });
}
/**
* 获取图片信息
*/
function getImageInfo(options) {
return wrapInvoke({ type: 'getImageInfo', data: options });
}
/**
* 警查询数据库大小:该API提供查询当前小程序所使用的数据库大小,便于ISV实时看当前使用情况,避免超出数据库大小限制。
*/
function queryDBSize() {
return wrapInvoke({ type: 'qn.queryDBSize' });
}
/**
* 数据库:千牛为小程序提供了数据库存储能力(my.database),但对插件数据库的大小做了限制,务必仔细最后一部分说明,未处理数据超限警告可能会导致数据库缓存被删除。
*/
function database(options) {
return wrapInvoke({ type: 'qn.database', data: options });
}
/**
* 获取文件信息
*/
function getFileInfo(options) {
return wrapInvoke({ type: 'getFileInfo', data: options });
}
/**
* 保存文件到本地
*/
function saveFile(options) {
return wrapInvoke({ type: 'saveFile', data: options });
}
/**
* 获取保存的文件信息
*/
function getSavedFileInfo(options) {
return wrapInvoke({ type: 'getSavedFileInfo', data: options });
}
/**
* 获取保存的所有文件信息
*/
function getSavedFileList() {
return wrapInvoke({ type: 'getSavedFileList' });
}
/**
* 删除某个保存的文件
*/
function removeSavedFile(options) {
return wrapInvoke({ type: 'removeSavedFile', data: options });
}
/**
* 选择文件
*/
function chooseFile(options) {
return wrapInvoke({ type: 'qn.chooseFile', data: options });
}
/**
* 打开文件并获取内容
*/
function chooseFileAndGetContent(options) {
return wrapInvoke({ type: 'qn.chooseFileAndGetContent', data: options });
}
/**
* 保存文件到磁盘
*/
function saveFileToDisk(options) {
return wrapInvoke({ type: 'qn.saveFileToDisk', data: options });
}
/**
* 清除本地数据缓存的异步接口
*/
function clearStorage() {
return wrapInvoke({ type: 'clearStorage' });
}
/**
* 清除本地数据缓存的同步接口
*/
function clearStorageSync() {
return wrapInvoke({ type: 'clearStorageSync' });
}
/**
* 获取缓存数据的异步接口
*/
function getStorage(options) {
return wrapInvoke({ type: 'getStorage', data: options });
}
/**
* 获取当前 storage 的相关信息的异步接口
*/
function getStorageInfo() {
return wrapInvoke({ type: 'getStorageInfo' });
}
/**
* 获取当前 storage 相关信息的同步接口
*/
function getStorageInfoSync() {
return wrapInvoke({ type: 'getStorageInfoSync' });
}
/**
* 获取缓存数据的同步接口
*/
function getStorageSync(options) {
return wrapInvoke({ type: 'getStorageSync', data: options });
}
/**
* 删除缓存数据的异步接口
*/
function removeStorage(options) {
return wrapInvoke({ type: 'removeStorage', data: options });
}
/**
* 删除缓存数据的异步接口
*/
function removeStorageSync(options) {
return wrapInvoke({ type: 'removeStorageSync', data: options });
}
/**
* 将数据存储在本地缓存中指定的 key 中的异步接口
*/
function setStorage(options) {
return wrapInvoke({ type: 'setStorage', data: options });
}
/**
* 同步将数据存储在本地缓存中指定的 key 中的同步接口
*/
function setStorageSync(options) {
return wrapInvoke({ type: 'setStorageSync', data: options });
}
/**
* 文件上传
*/
function uploadFile(options) {
return wrapInvoke({ type: 'uploadFile', data: options });
}
/**
* 文件上传
*/
function downloadFile(options) {
return wrapInvoke({ type: 'downloadFile', data: options });
}
/**
* 判断当前小程序的 API、入参或返回值、组件、属性等在当前版本是否支持
*/
function canIUse(apiName) {
return wrapInvoke({
type: 'canIUse',
data: apiName,
});
}
/**
* 获取基础库版本号
*/
function SDKVersion() {
return wrapInvoke({ type: 'SDKVersion' });
}
/**
* 获取手机系统信息的同步接口
*/
function getSystemInfoSync() {
return wrapInvoke({ type: 'getSystemInfoSync' });
}
/**
* 获取手机系统信息
*/
function getSystemInfo() {
return wrapInvoke({ type: 'getSystemInfo' });
}
/**
* 获取当前网络状态
*/
function getNetworkType() {
return wrapInvoke({ type: 'getNetworkType' });
}
/**
* 设置剪贴板数据
*/
function setClipboard(options) {
return wrapInvoke({ type: 'setClipboard', data: options });
}
/**
* 获取剪贴板数据
*/
function getClipboard() {
return wrapInvoke({ type: 'getClipboard' });
}
/**
* 获取服务器时间
*/
function getServerTime() {
return wrapInvoke({ type: 'getServerTime' });
}
/**
* 发起用户授权
*/
function authorize(options) {
return wrapInvoke({
type: 'authorize',
data: options,
});
}
/**
* 清除三方授权token
*/
function cleanToken() {
return wrapInvoke({
type: 'qn.cleanToken',
});
}
/**
* 弹出子账号授权框
*/
function showSubAccountAuth(options) {
return wrapInvoke({ type: 'qn.showSubAccountAuth', data: options });
}
/**
* 获取用户信息
*/
function getAuthUserInfo() {
return wrapInvoke({ type: 'getAuthUserInfo' });
}
/**
* 打开聊天
*/
function openChat(options) {
return wrapInvoke({ type: 'qn.openChat', data: options });
}
/**
* 获取当前IM旺旺联系人
*/
function imGetActiveUser() {
return wrapInvoke({ type: 'qn.imGetActiveUser' });
}
/**
* 打开千牛插件接口
*/
function openPlugin(options) {
return wrapInvoke({ type: 'qn.openPlugin', data: options });
}
/**
* 打开千牛的插槽协议。目前支持 shangpinguanli:itemList,itemDetail, jiaoyiguanli:tradeList,tradeDetail
*/
function openCategory(options) {
return wrapInvoke({ type: 'qn.openCategory', data: options });
}
/**
* 千牛提供更改商品价格的能力
*/
function changePrice(options) {
return wrapInvoke({
type: 'qn.changePrice',
data: options,
});
}
/**
* 跳转到其他小程序
*/
function navigateToMiniProgram(options) {
return wrapInvoke({ type: 'navigateToMiniProgram', data: options });
}
/**
* 退出当前小程序
*/
function exit() {
return wrapInvoke({ type: 'exit' });
}
/**
* 非对称加密
*/
function rsa(options) {
return wrapInvoke({ type: 'rsa', data: options });
}
/**
* 用于获取当前小程序的运行版本
*/
function getRunScene() {
return wrapInvoke({ type: 'getRunScene' });
}
/**
* 获取模板ext.json中的ext配置
*/
function getExtConfig() {
return wrapInvoke({ type: 'getExtConfig' });
}
/**
* 同步获取模板ext.json中的ext配置
*/
function getExtConfigSync() {
return wrapInvoke({ type: 'getExtConfigSync' });
}
export { alert, authorize, autoRegistry, canIUse, changePrice, chooseFile, chooseFileAndGetContent, chooseImage, cleanToken, clearStorage, clearStorageSync, closeQAP, compressImage, confirm, database, downloadFile, exit, getAuthUserInfo, getClipboard, getExtConfig, getExtConfigSync, getFileInfo, getImageInfo, getNetworkType, getRunScene, getSavedFileInfo, getSavedFileList, getServerTime, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, hideLoading, hideTabBar, hideTabBarRedDot, hideTabBarRedDotEx, hideTabEx, hideToast, imGetActiveUser, invoke, listen, navigateBack, navigateTo, navigateToMiniProgram, navigateToQAP, navigateToWebPage, openCategory, openChat, openPlugin, previewImage, queryDBSize, reLaunch, redirectTo, registry, removeListen, removeSavedFile, removeStorage, removeStorageSync, removeTabBarBadge, removeTabBarBadgeEx, rsa, saveFile, saveFileToDisk, saveImage, SDKVersion as sdkVersion, setClipboard, setStorage, setStorageSync, setTabBarBadge, setTabBarBadgeEx, setTabBarItem, showLoading, showSubAccountAuth, showTabBar, showTabBarRedDot, showTabBarRedDotEx, showTabEx, showToast, switchTab, switchTabEx, trigger, uploadFile };