u-parse.vue 21 KB

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