u-parse.vue 20 KB

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