wx_launch.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // info参数
  2. /*
  3. let params={
  4. eleId:"", // 元素ID
  5. appid:"", // 小程序id号 gh_****
  6. url:"", // 跳转小程序的页面路径地址 例: pages/home/home.html - (后面必须带上.html后缀 否则IOS跳转时出现小程序页面未配置)
  7. content:"" // html字符串 例: "<button>点我</button>"
  8. }
  9. */
  10. export function wx_launch(info){
  11. if (!is_weixn()) {
  12. return
  13. }
  14. if(!is_version()){
  15. var btn = document.getElementById(info.eleId); //获取元素
  16. let script = document.createElement("script");// 创建script内容插槽 避免template标签冲突
  17. script.type = "text/wxtag-template"; // 使用script插槽 必须定义这个type
  18. script.text = info.content // 自定义的html字符串内容
  19. let html = `<wx-open-launch-weapp style="width:100%;display:block;" username="${info.appid}" path="${info.url}">${script.outerHTML}</wx-open-launch-weapp>`;
  20. btn.innerHTML = html; // html字符串赋值
  21. // 点击按钮 正常跳转触发
  22. btn.addEventListener("launch", function (e) {
  23. console.log("success");
  24. });
  25. // 点击跳转 抛出异常
  26. btn.addEventListener("error", function (e) {
  27. console.log("fail", e.detail);
  28. alert(`跳转异常 - ${e.detail}`)
  29. });
  30. }else{
  31. alert("您的版本号不支持")
  32. }
  33. }
  34. // 判断是否微信环境
  35. function is_weixn() {
  36. let ua = navigator.userAgent.toLowerCase()
  37. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  38. return true
  39. } else {
  40. return false
  41. };
  42. };
  43. // 判断当前微信版本号是否支持
  44. function is_version(){
  45. let client = false; // 当前版本号是否支持 (默认不支持)
  46. let wxInfo = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i); // 微信浏览器信息
  47. // 微信版本号 wxInfo[1] = "7.0.18.1740" (示例)
  48. //进行split转成数组进行判断 [7,0,18,1740] (示例)
  49. let version = wxInfo[1].split(".");
  50. // 判断版本在7.0.12及以上的版本
  51. if (version[0] >= 7) {
  52. if (version[1] >= 0) {
  53. if (version[2] >= 12) {
  54. client = true; // 当前版本支持
  55. }
  56. }
  57. }
  58. return client;
  59. }