1
0

u-parse.vue 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. <template>
  2. <view class="u-parse">
  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. <u-trees :nodes="nodes" :lazyLoad="lazyLoad" :loading="loadingImg" :preview="preview"/>
  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 Parser from '../u-trees/MpHtmlParser.js'
  23. var cache = {};
  24. // #ifdef MP-WEIXIN || MP-TOUTIAO
  25. var fs = uni.getFileSystemManager ? uni.getFileSystemManager() : null;
  26. // #endif
  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. import cfg from '../u-trees/config.js'
  37. var {
  38. windowWidth,
  39. platform
  40. } = uni.getSystemInfoSync()
  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. * @property {Boolean} preview 点击图片是否自动预览
  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. emits: ["parse", "load", "ready", "error", "imgtap", "linkpress"],
  75. data() {
  76. return {
  77. // #ifdef H5 || MP-360
  78. uid: this._uid,
  79. // #endif
  80. // #ifdef APP-PLUS-NVUE
  81. height: 1,
  82. // #endif
  83. // #ifndef APP-PLUS-NVUE
  84. showAm: '',
  85. // #endif
  86. nodes: []
  87. }
  88. },
  89. props: {
  90. html: String,
  91. autopause: {
  92. type: Boolean,
  93. default: true
  94. },
  95. preview: {
  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. // #ifdef VUE2
  187. beforeDestroy() {
  188. // #ifdef H5 || MP-360
  189. if (this._observer) this._observer.disconnect();
  190. // #endif
  191. this.imgList.each(src => {
  192. // #ifdef APP-PLUS
  193. if (src && src.includes('_doc')) {
  194. plus.io.resolveLocalFileSystemURL(src, entry => {
  195. entry.remove();
  196. });
  197. }
  198. // #endif
  199. // #ifdef MP-WEIXIN || MP-TOUTIAO
  200. if (src && src.includes(uni.env.USER_DATA_PATH))
  201. fs && fs.unlink({
  202. filePath: src
  203. })
  204. // #endif
  205. })
  206. clearInterval(this._timer);
  207. },
  208. // #endif
  209. // #ifdef VUE3
  210. beforeUnmount() {
  211. // #ifdef H5 || MP-360
  212. if (this._observer) this._observer.disconnect();
  213. // #endif
  214. this.imgList.each(src => {
  215. // #ifdef APP-PLUS
  216. if (src && src.includes('_doc')) {
  217. plus.io.resolveLocalFileSystemURL(src, entry => {
  218. entry.remove();
  219. });
  220. }
  221. // #endif
  222. // #ifdef MP-WEIXIN || MP-TOUTIAO
  223. if (src && src.includes(uni.env.USER_DATA_PATH))
  224. fs && fs.unlink({
  225. filePath: src
  226. })
  227. // #endif
  228. })
  229. clearInterval(this._timer);
  230. },
  231. // #endif
  232. methods: {
  233. // 设置富文本内容
  234. setContent(html, append) {
  235. // #ifdef APP-PLUS-NVUE
  236. if (!html)
  237. return this.height = 1;
  238. if (append)
  239. this.$refs.web.evalJs("var b=document.createElement('div');b.innerHTML='" + html.replace(/'/g, "\\'") +
  240. "';document.getElementById('parser').appendChild(b)");
  241. else {
  242. html =
  243. '<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="' +
  244. this.domain + '"><div id="parser"' + (this.selectable ? '>' : ' style="user-select:none">') + this._handleHtml(html).replace(/\n/g, '\\n') +
  245. '</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"})},' +
  246. (this.showWithAnimation ? 'document.body.style.animation="_show .5s",' : '') +
  247. 'setTimeout(function(){e({action:"load",text:document.body.innerText,height:document.getElementById("parser").scrollHeight})},50);\x3c/script>';
  248. if (platform == 'android') html = html.replace(/%/g, '%25');
  249. this.$refs.web.evalJs("document.write('" + html.replace(/'/g, "\\'") + "');document.close()");
  250. }
  251. this.$refs.web.evalJs(
  252. '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"))>' +
  253. 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 + '",' : '') +
  254. '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})}' +
  255. (this.autopause ? ',h.onplay=function(){for(var e,t=0;e=y[t];t++)e!=this&&e.pause()}' : '') +
  256. ';for(var _,p=document.getElementsByTagName("audio"),w=0;_=p[w];w++)_.onerror=function(){e({action:"error",source:"audio",target:this})};' +
  257. (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)}' : '') +
  258. '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)'
  259. )
  260. this.nodes = [1];
  261. // #endif
  262. // #ifdef H5 || MP-360
  263. if (!html) {
  264. if (this.rtf && !append) this.rtf.parentNode.removeChild(this.rtf);
  265. return;
  266. }
  267. var div = document.createElement('div');
  268. if (!append) {
  269. if (this.rtf) this.rtf.parentNode.removeChild(this.rtf);
  270. this.rtf = div;
  271. } else {
  272. if (!this.rtf) this.rtf = div;
  273. else this.rtf.appendChild(div);
  274. }
  275. div.innerHTML = this._handleHtml(html, append);
  276. for (var styles = this.rtf.getElementsByTagName('style'), i = 0, style; style = styles[i++];) {
  277. style.innerHTML = style.innerHTML.replace(/body/g, '#rtf' + this._uid);
  278. style.setAttribute('scoped', 'true');
  279. }
  280. // 懒加载
  281. if (!this._observer && this.lazyLoad && IntersectionObserver) {
  282. this._observer = new IntersectionObserver(changes => {
  283. for (let item, i = 0; item = changes[i++];) {
  284. if (item.isIntersecting) {
  285. item.target.src = item.target.getAttribute('data-src');
  286. item.target.removeAttribute('data-src');
  287. this._observer.unobserve(item.target);
  288. }
  289. }
  290. }, {
  291. rootMargin: '500px 0px 500px 0px'
  292. })
  293. }
  294. var _ts = this;
  295. // 获取标题
  296. var title = this.rtf.getElementsByTagName('title');
  297. if (title.length && this.autosetTitle)
  298. uni.setNavigationBarTitle({
  299. title: title[0].innerText
  300. })
  301. // 填充 domain
  302. var fill = target => {
  303. var src = target.getAttribute('src');
  304. if (this.domain && src) {
  305. if (src[0] == '/') {
  306. if (src[1] == '/')
  307. target.src = (this.domain.includes('://') ? this.domain.split('://')[0] : '') + ':' + src;
  308. else target.src = this.domain + src;
  309. } else if (!src.includes('://') && src.indexOf('data:') != 0) target.src = this.domain + '/' + src;
  310. }
  311. }
  312. // 图片处理
  313. this.imgList.length = 0;
  314. var imgs = this.rtf.getElementsByTagName('img');
  315. for (let i = 0, j = 0, img; img = imgs[i]; i++) {
  316. if (parseInt(img.style.width || img.getAttribute('width')) > windowWidth)
  317. img.style.height = 'auto';
  318. fill(img);
  319. if (!img.hasAttribute('ignore') && img.parentElement.nodeName != 'A') {
  320. img.i = j++;
  321. _ts.imgList.push(img.getAttribute('original-src') || img.src || img.getAttribute('data-src'));
  322. img.onclick = function(e) {
  323. e.stopPropagation();
  324. var preview = _ts.preview;
  325. this.ignore = () => preview = false;
  326. _ts.$emit('imgtap', this);
  327. if (preview) {
  328. uni.previewImage({
  329. current: this.i,
  330. urls: _ts.imgList
  331. });
  332. }
  333. }
  334. }
  335. img.onerror = function() {
  336. if (cfg.errorImg)
  337. _ts.imgList[this.i] = this.src = cfg.errorImg;
  338. _ts.$emit('error', {
  339. source: 'img',
  340. target: this
  341. });
  342. }
  343. if (_ts.lazyLoad && this._observer && img.src && img.i != 0) {
  344. img.setAttribute('data-src', img.src);
  345. img.removeAttribute('src');
  346. this._observer.observe(img);
  347. }
  348. }
  349. // 链接处理
  350. var links = this.rtf.getElementsByTagName('a');
  351. for (var link of links) {
  352. link.onclick = function(e) {
  353. e.stopPropagation();
  354. var jump = true,
  355. href = this.getAttribute('href');
  356. _ts.$emit('linkpress', {
  357. href,
  358. ignore: () => jump = false
  359. });
  360. if (jump && href) {
  361. if (href[0] == '#') {
  362. if (_ts.useAnchor) {
  363. _ts.navigateTo({
  364. id: href.substr(1)
  365. })
  366. }
  367. } else if (href.indexOf('http') == 0 || href.indexOf('//') == 0)
  368. return true;
  369. else
  370. uni.navigateTo({
  371. url: href
  372. })
  373. }
  374. return false;
  375. }
  376. }
  377. // 视频处理
  378. var videos = this.rtf.getElementsByTagName('video');
  379. _ts.videoContexts = videos;
  380. for (let video, i = 0; video = videos[i++];) {
  381. fill(video);
  382. video.style.maxWidth = '100%';
  383. video.onerror = function() {
  384. _ts.$emit('error', {
  385. source: 'video',
  386. target: this
  387. });
  388. }
  389. video.onplay = function() {
  390. if (_ts.autopause)
  391. for (let item, i = 0; item = _ts.videoContexts[i++];)
  392. if (item != this) item.pause();
  393. }
  394. }
  395. // 音频处理
  396. var audios = this.rtf.getElementsByTagName('audio');
  397. for (var audio of audios) {
  398. fill(audio);
  399. audio.onerror = function() {
  400. _ts.$emit('error', {
  401. source: 'audio',
  402. target: this
  403. });
  404. }
  405. }
  406. // 表格处理
  407. if (this.autoscroll) {
  408. var tables = this.rtf.getElementsByTagName('table');
  409. for (var table of tables) {
  410. let div = document.createElement('div');
  411. div.style.overflow = 'scroll';
  412. table.parentNode.replaceChild(div, table);
  413. div.appendChild(table);
  414. }
  415. }
  416. if (!append) this.document.appendChild(this.rtf);
  417. this.$nextTick(() => {
  418. this.nodes = [1];
  419. this.$emit('load');
  420. });
  421. setTimeout(() => this.showAm = '', 500);
  422. // #endif
  423. // #ifndef APP-PLUS-NVUE
  424. // #ifndef H5 || MP-360
  425. var nodes;
  426. if (!html) return this.nodes = [];
  427. var parser = new Parser(html, this);
  428. // 缓存读取
  429. if (this.useCache) {
  430. var hashVal = hash(html);
  431. if (cache[hashVal])
  432. nodes = cache[hashVal];
  433. else {
  434. nodes = parser.parse();
  435. cache[hashVal] = nodes;
  436. }
  437. } else nodes = parser.parse();
  438. this.$emit('parse', nodes);
  439. if (append) this.nodes = this.nodes.concat(nodes);
  440. else this.nodes = nodes;
  441. if (nodes.length && nodes.title && this.autosetTitle)
  442. uni.setNavigationBarTitle({
  443. title: nodes.title
  444. })
  445. if (this.imgList) this.imgList.length = 0;
  446. this.videoContexts = [];
  447. this.$nextTick(() => {
  448. (function f(cs) {
  449. for (var i = cs.length; i--;) {
  450. if (cs[i].top) {
  451. cs[i].controls = [];
  452. cs[i].init();
  453. f(cs[i].$children);
  454. }
  455. }
  456. })(this.$children)
  457. this.$emit('load');
  458. })
  459. // #endif
  460. var height;
  461. clearInterval(this._timer);
  462. this._timer = setInterval(() => {
  463. // #ifdef H5 || MP-360
  464. this.rect = this.rtf.getBoundingClientRect();
  465. // #endif
  466. // #ifndef H5 || MP-360
  467. uni.createSelectorQuery().in(this)
  468. .select('#_top').boundingClientRect().exec(res => {
  469. if (!res) return;
  470. this.rect = res[0];
  471. // #endif
  472. if (this.rect.height == height) {
  473. this.$emit('ready', this.rect)
  474. clearInterval(this._timer);
  475. }
  476. height = this.rect.height;
  477. // #ifndef H5 || MP-360
  478. });
  479. // #endif
  480. }, 350);
  481. if (this.showWithAnimation && !append) this.showAm = 'animation:_show .5s';
  482. // #endif
  483. },
  484. // 获取文本内容
  485. getText(ns = this.nodes) {
  486. var txt = '';
  487. // #ifdef APP-PLUS-NVUE
  488. txt = this._text;
  489. // #endif
  490. // #ifdef H5 || MP-360
  491. txt = this.rtf.innerText;
  492. // #endif
  493. // #ifndef H5 || APP-PLUS-NVUE || MP-360
  494. for (var i = 0, n; n = ns[i++];) {
  495. if (n.type == 'text') txt += n.text.replace(/&nbsp;/g, '\u00A0').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  496. .replace(/&amp;/g, '&');
  497. else if (n.type == 'br') txt += '\n';
  498. else {
  499. // 块级标签前后加换行
  500. var block = n.name == 'p' || n.name == 'div' || n.name == 'tr' || n.name == 'li' || (n.name[0] == 'h' && n.name[1] >
  501. '0' && n.name[1] < '7');
  502. if (block && txt && txt[txt.length - 1] != '\n') txt += '\n';
  503. if (n.children) txt += this.getText(n.children);
  504. if (block && txt[txt.length - 1] != '\n') txt += '\n';
  505. else if (n.name == 'td' || n.name == 'th') txt += '\t';
  506. }
  507. }
  508. // #endif
  509. return txt;
  510. },
  511. // 锚点跳转
  512. in (obj) {
  513. if (obj.page && obj.selector && obj.scrollTop) this._in = obj;
  514. },
  515. navigateTo(obj) {
  516. if (!this.useAnchor) return obj.fail && obj.fail('Anchor is disabled');
  517. // #ifdef APP-PLUS-NVUE
  518. if (!obj.id)
  519. weexDom.scrollToElement(this.$refs.web);
  520. else
  521. this.$refs.web.evalJs('var pos=document.getElementById("' + obj.id +
  522. '");if(pos)post({action:"linkpress",href:"#",offset:pos.offsetTop+' + (obj.offset || 0) + '})');
  523. obj.success && obj.success();
  524. // #endif
  525. // #ifndef APP-PLUS-NVUE
  526. var d = ' ';
  527. // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
  528. d = '>>>';
  529. // #endif
  530. var selector = uni.createSelectorQuery().in(this._in ? this._in.page : this).select((this._in ? this._in.selector :
  531. '#_top') + (obj.id ? `${d}#${obj.id},${this._in?this._in.selector:'#_top'}${d}.${obj.id}` : '')).boundingClientRect();
  532. if (this._in) selector.select(this._in.selector).scrollOffset().select(this._in.selector).boundingClientRect();
  533. else selector.selectViewport().scrollOffset();
  534. selector.exec(res => {
  535. if (!res[0]) return obj.fail && obj.fail('Label not found')
  536. var scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + (obj.offset || 0);
  537. if (this._in) this._in.page[this._in.scrollTop] = scrollTop;
  538. else uni.pageScrollTo({
  539. scrollTop,
  540. duration: 300
  541. })
  542. obj.success && obj.success();
  543. })
  544. // #endif
  545. },
  546. // 获取视频对象
  547. getVideoContext(id) {
  548. // #ifndef APP-PLUS-NVUE
  549. if (!id) return this.videoContexts;
  550. else
  551. for (var i = this.videoContexts.length; i--;)
  552. if (this.videoContexts[i].id == id) return this.videoContexts[i];
  553. // #endif
  554. },
  555. // #ifdef H5 || APP-PLUS-NVUE || MP-360
  556. _handleHtml(html, append) {
  557. const classPrefix = ".u-parse ";
  558. if (!append) {
  559. // 处理 tag-style 和 userAgentStyles
  560. var style = `<style>@keyframes _show{0%{opacity:0}100%{opacity:1}}${classPrefix}img{max-width:100%}`;
  561. for (var item in cfg.userAgentStyles)
  562. style += `${classPrefix}${item}{${cfg.userAgentStyles[item]}}`;
  563. for (item in this.tagStyle)
  564. style += `${classPrefix}${item}{${this.tagStyle[item]}}`;
  565. style += '</style>';
  566. html = style + html;
  567. }
  568. // 处理 rpx
  569. if (html.includes('rpx'))
  570. html = html.replace(/[0-9.]+\s*rpx/g, $ => (parseFloat($) * windowWidth / 750) + 'px');
  571. return html;
  572. },
  573. // #endif
  574. // #ifdef APP-PLUS-NVUE
  575. _message(e) {
  576. var _ts = this;
  577. // 接收 web-view 消息
  578. var d = e.detail.data[0];
  579. switch (d.action) {
  580. case 'load':
  581. this.$emit('load');
  582. this.height = d.height;
  583. this._text = d.text;
  584. break;
  585. case 'getTitle':
  586. if (this.autosetTitle)
  587. uni.setNavigationBarTitle({
  588. title: d.title
  589. })
  590. break;
  591. case 'getImgList':
  592. this.imgList.length = 0;
  593. for (var i = d.imgList.length; i--;)
  594. this.imgList.setItem(i, d.imgList[i]);
  595. break;
  596. case 'preview':
  597. var preview = _ts.preview;
  598. d.img.ignore = () => preview = false;
  599. this.$emit('imgtap', d.img);
  600. if (preview)
  601. uni.previewImage({
  602. current: d.img.i,
  603. urls: this.imgList
  604. })
  605. break;
  606. case 'linkpress':
  607. var jump = true,
  608. href = d.href;
  609. this.$emit('linkpress', {
  610. href,
  611. ignore: () => jump = false
  612. })
  613. if (jump && href) {
  614. if (href[0] == '#') {
  615. if (this.useAnchor)
  616. weexDom.scrollToElement(this.$refs.web, {
  617. offset: d.offset
  618. })
  619. } else if (href.includes('://'))
  620. plus.runtime.openWeb(href);
  621. else
  622. uni.navigateTo({
  623. url: href
  624. })
  625. }
  626. break;
  627. case 'error':
  628. if (d.source == 'img' && cfg.errorImg)
  629. this.imgList.setItem(d.target.i, cfg.errorImg);
  630. this.$emit('error', {
  631. source: d.source,
  632. target: d.target
  633. })
  634. break;
  635. case 'ready':
  636. this.height = d.height;
  637. if (d.ready) uni.createSelectorQuery().in(this).select('#_top').boundingClientRect().exec(res => {
  638. this.rect = res[0];
  639. this.$emit('ready', res[0]);
  640. })
  641. break;
  642. case 'click':
  643. this.$emit('click');
  644. this.$emit('tap');
  645. }
  646. },
  647. // #endif
  648. }
  649. }
  650. </script>
  651. <style lang="scss" scoped>
  652. @keyframes _show {
  653. 0% {
  654. opacity: 0;
  655. }
  656. 100% {
  657. opacity: 1;
  658. }
  659. }
  660. /* #ifdef MP-WEIXIN */
  661. :host {
  662. display: block;
  663. overflow: auto;
  664. -webkit-overflow-scrolling: touch;
  665. }
  666. /* #endif */
  667. </style>