u-parse.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <template>
  2. <view>
  3. <slot v-if="!nodes.length" />
  4. <!--#ifdef APP-PLUS-NVUE-->
  5. <web-view id="_top" ref="web" :style="'margin-top:-2px;height:'+height+'px'" @onPostMessage="_message" />
  6. <!--#endif-->
  7. <!--#ifndef APP-PLUS-NVUE-->
  8. <view id="_top" :style="showAm+(selectable?';user-select:text;-webkit-user-select:text':'')">
  9. <!--#ifdef H5 || MP-360-->
  10. <div :id="'rtf'+uid"></div>
  11. <!--#endif-->
  12. <!--#ifndef H5 || MP-360-->
  13. <trees :nodes="nodes" :lazyLoad="lazyLoad" :loading="loadingImg" />
  14. <!--#endif-->
  15. </view>
  16. <!--#endif-->
  17. </view>
  18. </template>
  19. <script>
  20. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  21. import trees from './libs/trees';
  22. var cache = {},
  23. // #ifdef MP-WEIXIN || MP-TOUTIAO
  24. fs = uni.getFileSystemManager ? uni.getFileSystemManager() : null,
  25. // #endif
  26. Parser = require('./libs/MpHtmlParser.js');
  27. var dom;
  28. // 计算 cache 的 key
  29. function hash(str) {
  30. for (var i = str.length, val = 5381; i--;)
  31. val += (val << 5) + str.charCodeAt(i);
  32. return val;
  33. }
  34. // #endif
  35. // #ifdef H5 || APP-PLUS-NVUE || MP-360
  36. var {
  37. windowWidth,
  38. platform
  39. } = uni.getSystemInfoSync(),
  40. cfg = require('./libs/config.js');
  41. // #endif
  42. // #ifdef APP-PLUS-NVUE
  43. var weexDom = weex.requireModule('dom');
  44. // #endif
  45. /**
  46. * Parser 富文本组件
  47. * @tutorial https://github.com/jin-yufeng/Parser
  48. * @property {String} html 富文本数据
  49. * @property {Boolean} autopause 是否在播放一个视频时自动暂停其他视频
  50. * @property {Boolean} autoscroll 是否自动给所有表格添加一个滚动层
  51. * @property {Boolean} autosetTitle 是否自动将 title 标签中的内容设置到页面标题
  52. * @property {Number} compress 压缩等级
  53. * @property {String} domain 图片、视频等链接的主域名
  54. * @property {Boolean} lazyLoad 是否开启图片懒加载
  55. * @property {String} loadingImg 图片加载完成前的占位图
  56. * @property {Boolean} selectable 是否开启长按复制
  57. * @property {Object} tagStyle 标签的默认样式
  58. * @property {Boolean} showWithAnimation 是否使用渐显动画
  59. * @property {Boolean} useAnchor 是否使用锚点
  60. * @property {Boolean} useCache 是否缓存解析结果
  61. * @event {Function} parse 解析完成事件
  62. * @event {Function} load dom 加载完成事件
  63. * @event {Function} ready 所有图片加载完毕事件
  64. * @event {Function} error 错误事件
  65. * @event {Function} imgtap 图片点击事件
  66. * @event {Function} linkpress 链接点击事件
  67. * @author JinYufeng
  68. * @version 20201014
  69. * @listens MIT
  70. */
  71. export default {
  72. name: 'parser',
  73. data() {
  74. return {
  75. // #ifdef H5 || MP-360
  76. uid: this._uid,
  77. // #endif
  78. // #ifdef APP-PLUS-NVUE
  79. height: 1,
  80. // #endif
  81. // #ifndef APP-PLUS-NVUE
  82. showAm: '',
  83. // #endif
  84. nodes: []
  85. }
  86. },
  87. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  88. components: {
  89. trees
  90. },
  91. // #endif
  92. props: {
  93. html: String,
  94. autopause: {
  95. type: Boolean,
  96. default: true
  97. },
  98. autoscroll: Boolean,
  99. autosetTitle: {
  100. type: Boolean,
  101. default: true
  102. },
  103. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  104. compress: Number,
  105. loadingImg: String,
  106. useCache: Boolean,
  107. // #endif
  108. domain: String,
  109. lazyLoad: Boolean,
  110. selectable: Boolean,
  111. tagStyle: Object,
  112. showWithAnimation: Boolean,
  113. useAnchor: Boolean
  114. },
  115. watch: {
  116. html(html) {
  117. this.setContent(html);
  118. }
  119. },
  120. created() {
  121. // 图片数组
  122. this.imgList = [];
  123. this.imgList.each = function(f) {
  124. for (var i = 0, len = this.length; i < len; i++)
  125. this.setItem(i, f(this[i], i, this));
  126. }
  127. this.imgList.setItem = function(i, src) {
  128. if (i == void 0 || !src) return;
  129. // #ifndef MP-ALIPAY || APP-PLUS
  130. // 去重
  131. if (src.indexOf('http') == 0 && this.includes(src)) {
  132. var newSrc = src.split('://')[0];
  133. for (var j = newSrc.length, c; c = src[j]; j++) {
  134. if (c == '/' && src[j - 1] != '/' && src[j + 1] != '/') break;
  135. newSrc += Math.random() > 0.5 ? c.toUpperCase() : c;
  136. }
  137. newSrc += src.substr(j);
  138. return this[i] = newSrc;
  139. }
  140. // #endif
  141. this[i] = src;
  142. // 暂存 data src
  143. if (src.includes('data:image')) {
  144. var filePath, info = src.match(/data:image\/(\S+?);(\S+?),(.+)/);
  145. if (!info) return;
  146. // #ifdef MP-WEIXIN || MP-TOUTIAO
  147. filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.${info[1]}`;
  148. fs && fs.writeFile({
  149. filePath,
  150. data: info[3],
  151. encoding: info[2],
  152. success: () => this[i] = filePath
  153. })
  154. // #endif
  155. // #ifdef APP-PLUS
  156. filePath = `_doc/parser_tmp/${Date.now()}.${info[1]}`;
  157. var bitmap = new plus.nativeObj.Bitmap();
  158. bitmap.loadBase64Data(src, () => {
  159. bitmap.save(filePath, {}, () => {
  160. bitmap.clear()
  161. this[i] = filePath;
  162. })
  163. })
  164. // #endif
  165. }
  166. }
  167. },
  168. mounted() {
  169. // #ifdef H5 || MP-360
  170. this.document = document.getElementById('rtf' + this._uid);
  171. // #endif
  172. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  173. if (dom) this.document = new dom(this);
  174. // #endif
  175. // #ifdef APP-PLUS-NVUE
  176. this.document = this.$refs.web;
  177. setTimeout(() => {
  178. // #endif
  179. if (this.html) this.setContent(this.html);
  180. // #ifdef APP-PLUS-NVUE
  181. }, 30)
  182. // #endif
  183. },
  184. beforeDestroy() {
  185. // #ifdef H5 || MP-360
  186. if (this._observer) this._observer.disconnect();
  187. // #endif
  188. this.imgList.each(src => {
  189. // #ifdef APP-PLUS
  190. if (src && src.includes('_doc')) {
  191. plus.io.resolveLocalFileSystemURL(src, entry => {
  192. entry.remove();
  193. });
  194. }
  195. // #endif
  196. // #ifdef MP-WEIXIN || MP-TOUTIAO
  197. if (src && src.includes(uni.env.USER_DATA_PATH))
  198. fs && fs.unlink({
  199. filePath: src
  200. })
  201. // #endif
  202. })
  203. clearInterval(this._timer);
  204. },
  205. methods: {
  206. // 设置富文本内容
  207. setContent(html, append) {
  208. // #ifdef APP-PLUS-NVUE
  209. if (!html)
  210. return this.height = 1;
  211. if (append)
  212. this.$refs.web.evalJs("var b=document.createElement('div');b.innerHTML='" + html.replace(/'/g, "\\'") +
  213. "';document.getElementById('parser').appendChild(b)");
  214. else {
  215. html =
  216. '<meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><style>html,body{width:100%;height:100%;overflow:hidden}body{margin:0}</style><base href="' +
  217. this.domain + '"><div id="parser"' + (this.selectable ? '>' : ' style="user-select:none">') + this._handleHtml(html).replace(/\n/g, '\\n') +
  218. '</div><script>"use strict";function e(e){if(window.__dcloud_weex_postMessage||window.__dcloud_weex_){var t={data:[e]};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(t):window.__dcloud_weex_.postMessage(JSON.stringify(t))}}document.body.onclick=function(){e({action:"click"})},' +
  219. (this.showWithAnimation ? 'document.body.style.animation="_show .5s",' : '') +
  220. 'setTimeout(function(){e({action:"load",text:document.body.innerText,height:document.getElementById("parser").scrollHeight})},50);\x3c/script>';
  221. if (platform == 'android') html = html.replace(/%/g, '%25');
  222. this.$refs.web.evalJs("document.write('" + html.replace(/'/g, "\\'") + "');document.close()");
  223. }
  224. this.$refs.web.evalJs(
  225. 'var t=document.getElementsByTagName("title");t.length&&e({action:"getTitle",title:t[0].innerText});for(var o,n=document.getElementsByTagName("style"),r=1;o=n[r++];)o.innerHTML=o.innerHTML.replace(/body/g,"#parser");for(var a,c=document.getElementsByTagName("img"),s=[],i=0==c.length,d=0,l=0,g=0;a=c[l];l++)parseInt(a.style.width||a.getAttribute("width"))>' +
  226. windowWidth + '&&(a.style.height="auto"),a.onload=function(){++d==c.length&&(i=!0)},a.onerror=function(){++d==c.length&&(i=!0),' + (cfg.errorImg ? 'this.src="' + cfg.errorImg + '",' : '') +
  227. 'e({action:"error",source:"img",target:this})},a.hasAttribute("ignore")||"A"==a.parentElement.nodeName||(a.i=g++,s.push(a.getAttribute("original-src")||a.src||a.getAttribute("data-src")),a.onclick=function(){e({action:"preview",img:{i:this.i,src:this.src}})});e({action:"getImgList",imgList:s});for(var u,m=document.getElementsByTagName("a"),f=0;u=m[f];f++)u.onclick=function(){var t,o=this.getAttribute("href");if("#"==o[0]){var n=document.getElementById(o.substr(1));n&&(t=n.offsetTop)}return e({action:"linkpress",href:o,offset:t}),!1};for(var h,y=document.getElementsByTagName("video"),v=0;h=y[v];v++)h.style.maxWidth="100%",h.onerror=function(){e({action:"error",source:"video",target:this})}' +
  228. (this.autopause ? ',h.onplay=function(){for(var e,t=0;e=y[t];t++)e!=this&&e.pause()}' : '') +
  229. ';for(var _,p=document.getElementsByTagName("audio"),w=0;_=p[w];w++)_.onerror=function(){e({action:"error",source:"audio",target:this})};' +
  230. (this.autoscroll ? 'for(var T,E=document.getElementsByTagName("table"),B=0;T=E[B];B++){var N=document.createElement("div");N.style.overflow="scroll",T.parentNode.replaceChild(N,T),N.appendChild(T)}' : '') +
  231. 'var x=document.getElementById("parser");clearInterval(window.timer),window.timer=setInterval(function(){i&&clearInterval(window.timer),e({action:"ready",ready:i,height:x.scrollHeight})},350)'
  232. )
  233. this.nodes = [1];
  234. // #endif
  235. // #ifdef H5 || MP-360
  236. if (!html) {
  237. if (this.rtf && !append) this.rtf.parentNode.removeChild(this.rtf);
  238. return;
  239. }
  240. var div = document.createElement('div');
  241. if (!append) {
  242. if (this.rtf) this.rtf.parentNode.removeChild(this.rtf);
  243. this.rtf = div;
  244. } else {
  245. if (!this.rtf) this.rtf = div;
  246. else this.rtf.appendChild(div);
  247. }
  248. div.innerHTML = this._handleHtml(html, append);
  249. for (var styles = this.rtf.getElementsByTagName('style'), i = 0, style; style = styles[i++];) {
  250. style.innerHTML = style.innerHTML.replace(/body/g, '#rtf' + this._uid);
  251. style.setAttribute('scoped', 'true');
  252. }
  253. // 懒加载
  254. if (!this._observer && this.lazyLoad && IntersectionObserver) {
  255. this._observer = new IntersectionObserver(changes => {
  256. for (let item, i = 0; item = changes[i++];) {
  257. if (item.isIntersecting) {
  258. item.target.src = item.target.getAttribute('data-src');
  259. item.target.removeAttribute('data-src');
  260. this._observer.unobserve(item.target);
  261. }
  262. }
  263. }, {
  264. rootMargin: '500px 0px 500px 0px'
  265. })
  266. }
  267. var _ts = this;
  268. // 获取标题
  269. var title = this.rtf.getElementsByTagName('title');
  270. if (title.length && this.autosetTitle)
  271. uni.setNavigationBarTitle({
  272. title: title[0].innerText
  273. })
  274. // 图片处理
  275. this.imgList.length = 0;
  276. var imgs = this.rtf.getElementsByTagName('img');
  277. for (let i = 0, j = 0, img; img = imgs[i]; i++) {
  278. if (parseInt(img.style.width || img.getAttribute('width')) > windowWidth)
  279. img.style.height = 'auto';
  280. var src = img.getAttribute('src');
  281. if (this.domain && src) {
  282. if (src[0] == '/') {
  283. if (src[1] == '/')
  284. img.src = (this.domain.includes('://') ? this.domain.split('://')[0] : '') + ':' + src;
  285. else img.src = this.domain + src;
  286. } else if (!src.includes('://')) img.src = this.domain + '/' + src;
  287. }
  288. if (!img.hasAttribute('ignore') && img.parentElement.nodeName != 'A') {
  289. img.i = j++;
  290. _ts.imgList.push(img.getAttribute('original-src') || img.src || img.getAttribute('data-src'));
  291. img.onclick = function() {
  292. var preview = true;
  293. this.ignore = () => preview = false;
  294. _ts.$emit('imgtap', this);
  295. if (preview) {
  296. uni.previewImage({
  297. current: this.i,
  298. urls: _ts.imgList
  299. });
  300. }
  301. }
  302. }
  303. img.onerror = function() {
  304. if (cfg.errorImg)
  305. _ts.imgList[this.i] = this.src = cfg.errorImg;
  306. _ts.$emit('error', {
  307. source: 'img',
  308. target: this
  309. });
  310. }
  311. if (_ts.lazyLoad && this._observer && img.src && img.i != 0) {
  312. img.setAttribute('data-src', img.src);
  313. img.removeAttribute('src');
  314. this._observer.observe(img);
  315. }
  316. }
  317. // 链接处理
  318. var links = this.rtf.getElementsByTagName('a');
  319. for (var link of links) {
  320. link.onclick = function() {
  321. var jump = true,
  322. href = this.getAttribute('href');
  323. _ts.$emit('linkpress', {
  324. href,
  325. ignore: () => jump = false
  326. });
  327. if (jump && href) {
  328. if (href[0] == '#') {
  329. if (_ts.useAnchor) {
  330. _ts.navigateTo({
  331. id: href.substr(1)
  332. })
  333. }
  334. } else if (href.indexOf('http') == 0 || href.indexOf('//') == 0)
  335. return true;
  336. else
  337. uni.navigateTo({
  338. url: href
  339. })
  340. }
  341. return false;
  342. }
  343. }
  344. // 视频处理
  345. var videos = this.rtf.getElementsByTagName('video');
  346. _ts.videoContexts = videos;
  347. for (let video, i = 0; video = videos[i++];) {
  348. video.style.maxWidth = '100%';
  349. video.onerror = function() {
  350. _ts.$emit('error', {
  351. source: 'video',
  352. target: this
  353. });
  354. }
  355. video.onplay = function() {
  356. if (_ts.autopause)
  357. for (let item, i = 0; item = _ts.videoContexts[i++];)
  358. if (item != this) item.pause();
  359. }
  360. }
  361. // 音频处理
  362. var audios = this.rtf.getElementsByTagName('audio');
  363. for (var audio of audios)
  364. audio.onerror = function() {
  365. _ts.$emit('error', {
  366. source: 'audio',
  367. target: this
  368. });
  369. }
  370. // 表格处理
  371. if (this.autoscroll) {
  372. var tables = this.rtf.getElementsByTagName('table');
  373. for (var table of tables) {
  374. let div = document.createElement('div');
  375. div.style.overflow = 'scroll';
  376. table.parentNode.replaceChild(div, table);
  377. div.appendChild(table);
  378. }
  379. }
  380. if (!append) this.document.appendChild(this.rtf);
  381. this.$nextTick(() => {
  382. this.nodes = [1];
  383. this.$emit('load');
  384. });
  385. setTimeout(() => this.showAm = '', 500);
  386. // #endif
  387. // #ifndef APP-PLUS-NVUE
  388. // #ifndef H5 || MP-360
  389. var nodes;
  390. if (!html) return this.nodes = [];
  391. var parser = new Parser(html, this);
  392. // 缓存读取
  393. if (this.useCache) {
  394. var hashVal = hash(html);
  395. if (cache[hashVal])
  396. nodes = cache[hashVal];
  397. else {
  398. nodes = parser.parse();
  399. cache[hashVal] = nodes;
  400. }
  401. } else nodes = parser.parse();
  402. this.$emit('parse', nodes);
  403. if (append) this.nodes = this.nodes.concat(nodes);
  404. else this.nodes = nodes;
  405. if (nodes.length && nodes.title && this.autosetTitle)
  406. uni.setNavigationBarTitle({
  407. title: nodes.title
  408. })
  409. if (this.imgList) this.imgList.length = 0;
  410. this.videoContexts = [];
  411. this.$nextTick(() => {
  412. (function f(cs) {
  413. for (var i = cs.length; i--;) {
  414. if (cs[i].top) {
  415. cs[i].controls = [];
  416. cs[i].init();
  417. f(cs[i].$children);
  418. }
  419. }
  420. })(this.$children)
  421. this.$emit('load');
  422. })
  423. // #endif
  424. var height;
  425. clearInterval(this._timer);
  426. this._timer = setInterval(() => {
  427. // #ifdef H5 || MP-360
  428. this.rect = this.rtf.getBoundingClientRect();
  429. // #endif
  430. // #ifndef H5 || MP-360
  431. uni.createSelectorQuery().in(this)
  432. .select('#_top').boundingClientRect().exec(res => {
  433. if (!res) return;
  434. this.rect = res[0];
  435. // #endif
  436. if (this.rect.height == height) {
  437. this.$emit('ready', this.rect)
  438. clearInterval(this._timer);
  439. }
  440. height = this.rect.height;
  441. // #ifndef H5 || MP-360
  442. });
  443. // #endif
  444. }, 350);
  445. if (this.showWithAnimation && !append) this.showAm = 'animation:_show .5s';
  446. // #endif
  447. },
  448. // 获取文本内容
  449. getText(ns = this.nodes) {
  450. var txt = '';
  451. // #ifdef APP-PLUS-NVUE
  452. txt = this._text;
  453. // #endif
  454. // #ifdef H5 || MP-360
  455. txt = this.rtf.innerText;
  456. // #endif
  457. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  458. for (var i = 0, n; n = ns[i++];) {
  459. if (n.type == 'text') txt += n.text.replace(/&nbsp;/g, '\u00A0').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  460. .replace(/&amp;/g, '&');
  461. else if (n.type == 'br') txt += '\n';
  462. else {
  463. // 块级标签前后加换行
  464. var block = n.name == 'p' || n.name == 'div' || n.name == 'tr' || n.name == 'li' || (n.name[0] == 'h' && n.name[1] >
  465. '0' && n.name[1] < '7');
  466. if (block && txt && txt[txt.length - 1] != '\n') txt += '\n';
  467. if (n.children) txt += this.getText(n.children);
  468. if (block && txt[txt.length - 1] != '\n') txt += '\n';
  469. else if (n.name == 'td' || n.name == 'th') txt += '\t';
  470. }
  471. }
  472. // #endif
  473. return txt;
  474. },
  475. // 锚点跳转
  476. in (obj) {
  477. if (obj.page && obj.selector && obj.scrollTop) this._in = obj;
  478. },
  479. navigateTo(obj) {
  480. if (!this.useAnchor) return obj.fail && obj.fail('Anchor is disabled');
  481. // #ifdef APP-PLUS-NVUE
  482. if (!obj.id)
  483. weexDom.scrollToElement(this.$refs.web);
  484. else
  485. this.$refs.web.evalJs('var pos=document.getElementById("' + obj.id +
  486. '");if(pos)post({action:"linkpress",href:"#",offset:pos.offsetTop+' + (obj.offset || 0) + '})');
  487. obj.success && obj.success();
  488. // #endif
  489. // #ifndef APP-PLUS-NVUE
  490. var d = ' ';
  491. // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
  492. d = '>>>';
  493. // #endif
  494. var selector = uni.createSelectorQuery().in(this._in ? this._in.page : this).select((this._in ? this._in.selector :
  495. '#_top') + (obj.id ? `${d}#${obj.id},${this._in?this._in.selector:'#_top'}${d}.${obj.id}` : '')).boundingClientRect();
  496. if (this._in) selector.select(this._in.selector).scrollOffset().select(this._in.selector).boundingClientRect();
  497. else selector.selectViewport().scrollOffset();
  498. selector.exec(res => {
  499. if (!res[0]) return obj.fail && obj.fail('Label not found')
  500. var scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + (obj.offset || 0);
  501. if (this._in) this._in.page[this._in.scrollTop] = scrollTop;
  502. else uni.pageScrollTo({
  503. scrollTop,
  504. duration: 300
  505. })
  506. obj.success && obj.success();
  507. })
  508. // #endif
  509. },
  510. // 获取视频对象
  511. getVideoContext(id) {
  512. // #ifndef APP-PLUS-NVUE
  513. if (!id) return this.videoContexts;
  514. else
  515. for (var i = this.videoContexts.length; i--;)
  516. if (this.videoContexts[i].id == id) return this.videoContexts[i];
  517. // #endif
  518. },
  519. // #ifdef H5 || APP-PLUS-NVUE || MP-360
  520. _handleHtml(html, append) {
  521. if (!append) {
  522. // 处理 tag-style 和 userAgentStyles
  523. var style = '<style>@keyframes _show{0%{opacity:0}100%{opacity:1}}img{max-width:100%}';
  524. for (var item in cfg.userAgentStyles)
  525. style += `${item}{${cfg.userAgentStyles[item]}}`;
  526. for (item in this.tagStyle)
  527. style += `${item}{${this.tagStyle[item]}}`;
  528. style += '</style>';
  529. html = style + html;
  530. }
  531. // 处理 rpx
  532. if (html.includes('rpx'))
  533. html = html.replace(/[0-9.]+\s*rpx/g, $ => (parseFloat($) * windowWidth / 750) + 'px');
  534. return html;
  535. },
  536. // #endif
  537. // #ifdef APP-PLUS-NVUE
  538. _message(e) {
  539. // 接收 web-view 消息
  540. var d = e.detail.data[0];
  541. switch (d.action) {
  542. case 'load':
  543. this.$emit('load');
  544. this.height = d.height;
  545. this._text = d.text;
  546. break;
  547. case 'getTitle':
  548. if (this.autosetTitle)
  549. uni.setNavigationBarTitle({
  550. title: d.title
  551. })
  552. break;
  553. case 'getImgList':
  554. this.imgList.length = 0;
  555. for (var i = d.imgList.length; i--;)
  556. this.imgList.setItem(i, d.imgList[i]);
  557. break;
  558. case 'preview':
  559. var preview = true;
  560. d.img.ignore = () => preview = false;
  561. this.$emit('imgtap', d.img);
  562. if (preview)
  563. uni.previewImage({
  564. current: d.img.i,
  565. urls: this.imgList
  566. })
  567. break;
  568. case 'linkpress':
  569. var jump = true,
  570. href = d.href;
  571. this.$emit('linkpress', {
  572. href,
  573. ignore: () => jump = false
  574. })
  575. if (jump && href) {
  576. if (href[0] == '#') {
  577. if (this.useAnchor)
  578. weexDom.scrollToElement(this.$refs.web, {
  579. offset: d.offset
  580. })
  581. } else if (href.includes('://'))
  582. plus.runtime.openWeb(href);
  583. else
  584. uni.navigateTo({
  585. url: href
  586. })
  587. }
  588. break;
  589. case 'error':
  590. if (d.source == 'img' && cfg.errorImg)
  591. this.imgList.setItem(d.target.i, cfg.errorImg);
  592. this.$emit('error', {
  593. source: d.source,
  594. target: d.target
  595. })
  596. break;
  597. case 'ready':
  598. this.height = d.height;
  599. if (d.ready) uni.createSelectorQuery().in(this).select('#_top').boundingClientRect().exec(res => {
  600. this.rect = res[0];
  601. this.$emit('ready', res[0]);
  602. })
  603. break;
  604. case 'click':
  605. this.$emit('click');
  606. this.$emit('tap');
  607. }
  608. },
  609. // #endif
  610. }
  611. }
  612. </script>
  613. <style>
  614. @keyframes _show {
  615. 0% {
  616. opacity: 0;
  617. }
  618. 100% {
  619. opacity: 1;
  620. }
  621. }
  622. /* #ifdef MP-WEIXIN */
  623. :host {
  624. display: block;
  625. overflow: scroll;
  626. -webkit-overflow-scrolling: touch;
  627. }
  628. /* #endif */
  629. </style>