web-view-target.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Keep query strings intact on both raw and WeChat-encoded page options.
  2. function readTarget(value) {
  3. if (typeof value !== 'string' || !value || value.length > 8192) return '';
  4. let target = value;
  5. if (!target.startsWith('https://')) {
  6. try { target = decodeURIComponent(value); } catch (_) { return ''; }
  7. }
  8. if (/[\\\s\u0000-\u001f]/.test(target)) return '';
  9. const matched = /^https:\/\/([^/?#]+)([^?#]*)(?:[?#]|$)/.exec(target);
  10. if (!matched) return '';
  11. if (matched[1] === 'www.yuban.co') return target;
  12. if (matched[1] === 'app.fmode.cn' && /^\/dev\/pobingfeng\/owner\/nav\/(?:products|cases|home)\/?$/.test(matched[2])) return target;
  13. return '';
  14. }
  15. function queryKey(part) {
  16. try { return decodeURIComponent(part.split('=')[0]); } catch (_) { return ''; }
  17. }
  18. function withQuery(target, values = {}, removeIdentity = false) {
  19. const hashAt = target.indexOf('#');
  20. const url = hashAt < 0 ? target : target.slice(0, hashAt);
  21. const hash = hashAt < 0 ? '' : target.slice(hashAt);
  22. const index = url.indexOf('?');
  23. const base = index < 0 ? url : url.slice(0, index);
  24. let parts = index < 0 ? [] : url.slice(index + 1).split('&').filter(Boolean);
  25. if (removeIdentity) parts = parts.filter(part => !['token','userId','mobile'].includes(queryKey(part)));
  26. const keys = new Set(parts.map(queryKey));
  27. for (const [key,value] of Object.entries(values)) {
  28. if (keys.has(key) || value === '' || value == null) continue;
  29. parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(value)));
  30. }
  31. return base + (parts.length ? '?' + parts.join('&') : '') + hash;
  32. }
  33. function requestedTarget(options = {}) {
  34. const target = readTarget(options.path);
  35. if (!target) return '';
  36. const values = {};
  37. for (const [key,value] of Object.entries(options)) {
  38. if (!['path','url','skipAuth','token','userId','mobile','__proto__','constructor','prototype'].includes(key) && typeof value === 'string') values[key] = value;
  39. }
  40. return withQuery(target, values, true);
  41. }
  42. module.exports = { readTarget, requestedTarget, withQuery };