webview-polyfill.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /**
  2. * <webview> 的 Web 实现
  3. * ====================
  4. * 品牌插件(client.js)用 `document.createElement("webview")` 挂右侧平台页面,
  5. * 这是 Electron 专有标签,普通浏览器里没有。这个文件把它补成一个自定义元素:
  6. *
  7. * 元素 = 一块 canvas(画服务端 Chromium 的画面)+ 一个隐藏输入框(接键盘/输入法)
  8. * 属性 = src / partition / name 全部接受,值不参与逻辑(partition 是 Electron 会话概念)
  9. * 方法 = loadURL / reload / getURL / openDevTools
  10. * 事件 = did-start-loading / did-stop-loading / page-title-updated / did-fail-load
  11. *
  12. * 关键行为:**从 DOM 上摘下来再挂回去不重新加载**。
  13. * 桌面端为此专门把 webview 提成模块级单例(切会话时只是 detach),Web 版靠服务端
  14. * 页签常驻来实现同样的语义:attach 只重连画面,不导航。
  15. */
  16. (function () {
  17. 'use strict'
  18. if (window.customElements && window.customElements.get('webview')) return
  19. var WS = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/_cc/rt?tab='
  20. /**
  21. * API 模式:服务端不代理浏览器,右侧栏没有画面可接。
  22. * 这时 <webview> 降级成一张卡片 —— 地址交给老师自己的浏览器打开
  23. * (同域,登录态在老师本机),元素的方法与事件仍然照常触发,
  24. * 品牌插件那侧不需要改一行。
  25. */
  26. var EXTERNAL = !!(window.__CC__ && window.__CC__.pageMode && window.__CC__.pageMode !== 'browser')
  27. function hostOf (url) {
  28. try { return new URL(url).host } catch (err) { return '' }
  29. }
  30. function post (path, body) {
  31. return fetch(location.origin + path, {
  32. method: 'POST',
  33. credentials: 'same-origin',
  34. headers: { 'content-type': 'application/json' },
  35. body: JSON.stringify(body || {})
  36. }).then(function (res) { return res.json() })
  37. }
  38. function emit (el, type, props) {
  39. var event = new Event(type)
  40. if (props) Object.assign(event, props)
  41. el.dispatchEvent(event)
  42. }
  43. function mods (event) {
  44. return (event.shiftKey ? 1 : 0) | (event.altKey ? 1 << 1 : 0) | (event.ctrlKey ? 1 << 2 : 0) | (event.metaKey ? 1 << 3 : 0)
  45. }
  46. var SPECIAL_KEYS = {
  47. Enter: 1, Tab: 1, Escape: 1, Backspace: 1, Delete: 1, ArrowUp: 1, ArrowDown: 1,
  48. ArrowLeft: 1, ArrowRight: 1, Home: 1, End: 1, PageUp: 1, PageDown: 1
  49. }
  50. class CocoWebview extends HTMLElement {
  51. constructor () {
  52. super()
  53. this._url = ''
  54. this._tabId = ''
  55. this._ws = null
  56. this._retry = 0
  57. this._timer = null
  58. this._attaching = null
  59. this._lastClick = 0
  60. this._clickCount = 1
  61. this._pendingFrame = false
  62. this._lastSize = { w: 0, h: 0 }
  63. this._observer = null
  64. this._built = false
  65. }
  66. // ---------------------------------------------------------------- DOM
  67. #build () {
  68. if (this._built) return
  69. this._built = true
  70. if (EXTERNAL) return this.#buildCard()
  71. var wrap = document.createElement('div')
  72. wrap.style.cssText = 'position:relative;flex:1;width:100%;height:100%;overflow:hidden;background:#fff;'
  73. var canvas = document.createElement('canvas')
  74. canvas.style.cssText = 'width:100%;height:100%;display:block;touch-action:none;cursor:default;outline:none;'
  75. canvas.width = 1280
  76. canvas.height = 800
  77. // 键盘接这里:真实输入框才能唤起输入法候选窗,也能拿到粘贴
  78. var sink = document.createElement('textarea')
  79. sink.setAttribute('autocomplete', 'off')
  80. sink.setAttribute('autocorrect', 'off')
  81. sink.setAttribute('autocapitalize', 'off')
  82. sink.setAttribute('spellcheck', 'false')
  83. sink.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;' +
  84. 'border:0;padding:0;resize:none;overflow:hidden;z-index:1;'
  85. wrap.appendChild(canvas)
  86. wrap.appendChild(sink)
  87. this.appendChild(wrap)
  88. this.style.display = this.style.display || 'flex'
  89. this._canvas = canvas
  90. this._ctx = canvas.getContext('2d', { alpha: false })
  91. this._sink = sink
  92. this._bind()
  93. }
  94. /** API 模式的呈现:没有画面,只有一个"去浏览器打开"的入口 */
  95. #buildCard () {
  96. var wrap = document.createElement('div')
  97. wrap.style.cssText = 'flex:1;width:100%;height:100%;display:flex;align-items:center;' +
  98. 'justify-content:center;background:#f7f8fa;'
  99. var card = document.createElement('div')
  100. card.style.cssText = 'max-width:420px;text-align:center;padding:28px 24px;border:1px solid #e5e6eb;' +
  101. 'border-radius:12px;background:#fff;box-shadow:0 2px 8px rgba(0,0,0,.04);'
  102. var title = document.createElement('div')
  103. title.style.cssText = 'font:600 15px/1.5 -apple-system,"Segoe UI",system-ui,"PingFang SC",sans-serif;' +
  104. 'color:#1d2129;margin-bottom:8px;word-break:break-all;'
  105. title.textContent = '平台页面'
  106. var desc = document.createElement('div')
  107. desc.style.cssText = 'font:13px/1.7 -apple-system,"Segoe UI",system-ui,"PingFang SC",sans-serif;' +
  108. 'color:#86909c;margin-bottom:16px;'
  109. desc.textContent = '本次部署不代理浏览器。点下面的按钮,在你自己浏览器的标签页里打开,登录态和平时一致。'
  110. var btn = document.createElement('a')
  111. btn.target = '_blank'
  112. btn.rel = 'noopener noreferrer'
  113. btn.textContent = '在浏览器打开'
  114. btn.style.cssText = 'display:inline-block;padding:8px 18px;border-radius:8px;background:#165DFF;' +
  115. 'color:#fff;text-decoration:none;font:500 14px/1.4 -apple-system,"Segoe UI",system-ui,sans-serif;'
  116. btn.addEventListener('click', () => {
  117. // 老师主动点了才算"打开成功":把插件的 loading 态收尾,避免右侧栏一直转圈
  118. emit(this, 'page-title-updated', { title: hostOf(this._url) })
  119. emit(this, 'did-stop-loading')
  120. })
  121. card.appendChild(title)
  122. card.appendChild(desc)
  123. card.appendChild(btn)
  124. wrap.appendChild(card)
  125. this.appendChild(wrap)
  126. this.style.display = this.style.display || 'flex'
  127. this._cardTitle = title
  128. this._cardDesc = desc
  129. this._cardBtn = btn
  130. this.#updateCard()
  131. }
  132. #updateCard () {
  133. if (!this._cardBtn) return
  134. var url = this._url || ''
  135. this._cardBtn.href = url || '#'
  136. this._cardBtn.style.opacity = url ? '1' : '.45'
  137. this._cardBtn.style.pointerEvents = url ? 'auto' : 'none'
  138. if (url) {
  139. this._cardTitle.textContent = hostOf(url) || '平台页面'
  140. this._cardDesc.textContent =
  141. '本次部署不代理浏览器。点下面的按钮,在你自己浏览器的标签页里打开,登录态和平时一致。'
  142. }
  143. }
  144. connectedCallback () {
  145. this.#build()
  146. if (this._url) this.#attach(this._url)
  147. this.#observeSize()
  148. }
  149. disconnectedCallback () {
  150. // 只断开画面传输,不动服务端页签:挂回来还是原来那一页
  151. this.#closeSocket()
  152. if (this._observer) { this._observer.disconnect(); this._observer = null }
  153. }
  154. attributeChangedCallback (name, oldValue, value) {
  155. if (name === 'src' && value && value !== oldValue) this.loadURL(value)
  156. }
  157. static get observedAttributes () { return ['src'] }
  158. get src () { return this._url }
  159. set src (value) { this.loadURL(value) }
  160. getURL () { return this._url }
  161. // ---------------------------------------------------------------- 导航
  162. /** 明确要求换地址(桌面端"目标变了才导航"的语义) */
  163. loadURL (url) {
  164. var target = String(url || '').trim()
  165. if (!/^https?:\/\//i.test(target)) return Promise.resolve({ ok: false, error: 'bad-url' })
  166. this._url = target
  167. emit(this, 'did-start-loading')
  168. if (EXTERNAL) {
  169. this.#build()
  170. this.#updateCard()
  171. // 没有真的在加载,但插件在 did-stop-loading 里收尾,必须给一次
  172. setTimeout(() => {
  173. emit(this, 'page-title-updated', { title: hostOf(target) })
  174. emit(this, 'did-stop-loading')
  175. }, 0)
  176. return Promise.resolve({ ok: true, mode: 'external', url: target })
  177. }
  178. return post('/_cc/api/browser/open', { url: target })
  179. .then((res) => {
  180. if (!res || !res.ok) {
  181. emit(this, 'did-fail-load', { errorDescription: (res && res.error) || 'open-failed', isMainFrame: true })
  182. return res || { ok: false }
  183. }
  184. this._tabId = res.tabId
  185. this._retry = 0
  186. this.#connect()
  187. return res
  188. })
  189. .catch((err) => {
  190. emit(this, 'did-fail-load', { errorDescription: err.message, isMainFrame: true })
  191. return { ok: false, error: err.message }
  192. })
  193. }
  194. /** 挂回 DOM 时用:有同站页签就接上,没有才新建(绝不因为"切会话"刷新页面) */
  195. #attach (url) {
  196. if (EXTERNAL) {
  197. // 没有服务端页签可接,地址留着给卡片按钮用
  198. if (!this._url && url) this._url = String(url)
  199. this.#build()
  200. this.#updateCard()
  201. return Promise.resolve(null)
  202. }
  203. if (this._attaching) return this._attaching
  204. this._attaching = post('/_cc/api/browser/attach', { url })
  205. .then((res) => {
  206. this._attaching = null
  207. if (!res || !res.ok) return null
  208. this._tabId = res.tabId
  209. if (res.url) this._url = res.url
  210. this.#connect()
  211. return res
  212. })
  213. .catch(() => { this._attaching = null; return null })
  214. return this._attaching
  215. }
  216. reload () {
  217. if (EXTERNAL) {
  218. // 刷新的是老师自己浏览器里的标签,这里只做状态回放
  219. emit(this, 'did-start-loading')
  220. setTimeout(() => emit(this, 'did-stop-loading'), 0)
  221. return Promise.resolve({ ok: true, mode: 'external' })
  222. }
  223. return post('/_cc/api/browser/reload', { tabId: this._tabId, hard: false })
  224. }
  225. openDevTools () { /* headless 里没有 F12;控制台走右侧面板的日志条 */ }
  226. // ---------------------------------------------------------------- 连接
  227. #connect () {
  228. if (EXTERNAL) return
  229. if (!this._tabId) return
  230. if (this._ws && this._ws.readyState <= 1 && this._ws._tabId === this._tabId) return
  231. this.#closeSocket()
  232. var ws
  233. try { ws = new WebSocket(WS + encodeURIComponent(this._tabId)) } catch (err) { return this.#scheduleRetry() }
  234. ws.binaryType = 'blob'
  235. ws._tabId = this._tabId
  236. this._ws = ws
  237. ws.onopen = () => {
  238. this._retry = 0
  239. // 尺寸先发过去:服务端按这个尺寸设视口,画面才和画布一样大
  240. this.#sendSize(true)
  241. }
  242. ws.onmessage = (event) => {
  243. if (typeof event.data === 'string') {
  244. this.#control(event.data)
  245. return
  246. }
  247. this.#frame(event.data)
  248. }
  249. ws.onclose = () => {
  250. if (this._ws === ws) this._ws = null
  251. if (this.isConnected) this.#scheduleRetry()
  252. }
  253. ws.onerror = () => { /* onclose 会跟着来 */ }
  254. }
  255. #closeSocket () {
  256. var ws = this._ws
  257. this._ws = null
  258. if (ws) { try { ws.close() } catch (err) { /* 已经关了 */ } }
  259. }
  260. #scheduleRetry () {
  261. if (this._timer) return
  262. var delay = Math.min(800 * Math.pow(1.6, this._retry++), 8000)
  263. this._timer = setTimeout(() => {
  264. this._timer = null
  265. if (this.isConnected) this.#connect()
  266. }, delay)
  267. }
  268. #control (raw) {
  269. var msg = null
  270. try { msg = JSON.parse(raw) } catch (err) { return }
  271. if (msg.t === 'state') {
  272. if (msg.field === 'title') emit(this, 'page-title-updated', { title: msg.value })
  273. else if (msg.field === 'loading') emit(this, msg.value ? 'did-start-loading' : 'did-stop-loading')
  274. else if (msg.field === 'error') {
  275. emit(this, 'did-fail-load', { errorDescription: msg.value, isMainFrame: true })
  276. } else if (msg.field === 'url' && msg.value) {
  277. this._url = msg.value
  278. }
  279. return
  280. }
  281. if (msg.t === 'log') {
  282. this.__ccLogs = this.__ccLogs || []
  283. this.__ccLogs.push(msg)
  284. if (this.__ccLogs.length > 200) this.__ccLogs.shift()
  285. this.dispatchEvent(new CustomEvent('cc-log', { detail: msg }))
  286. }
  287. }
  288. #frame (blob) {
  289. if (this._pendingFrame) return // 上一帧还没画完,丢掉这一帧(画面不会因此滞后)
  290. this._pendingFrame = true
  291. var self = this
  292. createImageBitmap(blob).then(function (bmp) {
  293. var canvas = self._canvas
  294. if (!canvas || !self._ctx) { bmp.close && bmp.close(); return }
  295. if (canvas.width !== bmp.width || canvas.height !== bmp.height) {
  296. canvas.width = bmp.width
  297. canvas.height = bmp.height
  298. }
  299. self._ctx.drawImage(bmp, 0, 0)
  300. bmp.close && bmp.close()
  301. }).catch(function () { /* 半帧/坏帧,跳过 */ }).then(function () {
  302. self._pendingFrame = false
  303. })
  304. }
  305. // ---------------------------------------------------------------- 尺寸
  306. #observeSize () {
  307. if (this._observer || typeof ResizeObserver === 'undefined') return
  308. this._observer = new ResizeObserver(() => this.#sendSize(false))
  309. this._observer.observe(this)
  310. this.#sendSize(true)
  311. }
  312. #sendSize (force) {
  313. var rect = this.getBoundingClientRect()
  314. var w = Math.round(rect.width)
  315. var h = Math.round(rect.height)
  316. if (w < 50 || h < 50) return
  317. if (!force && Math.abs(w - this._lastSize.w) < 8 && Math.abs(h - this._lastSize.h) < 8) return
  318. this._lastSize = { w: w, h: h }
  319. this.#send({ t: 'resize', w: w, h: h })
  320. }
  321. // ---------------------------------------------------------------- 输入
  322. #send (msg) {
  323. var ws = this._ws
  324. if (ws && ws.readyState === 1) {
  325. try { ws.send(JSON.stringify(msg)) } catch (err) { /* 连接刚断 */ }
  326. }
  327. }
  328. #point (event) {
  329. var rect = this._canvas.getBoundingClientRect()
  330. var scaleX = this._canvas.width / Math.max(rect.width, 1)
  331. var scaleY = this._canvas.height / Math.max(rect.height, 1)
  332. return {
  333. x: Math.round((event.clientX - rect.left) * scaleX),
  334. y: Math.round((event.clientY - rect.top) * scaleY)
  335. }
  336. }
  337. #bind () {
  338. var canvas = this._canvas
  339. var sink = this._sink
  340. var self = this
  341. canvas.addEventListener('pointerdown', (event) => {
  342. event.preventDefault()
  343. sink.focus({ preventScroll: true })
  344. var now = Date.now()
  345. this._clickCount = (now - this._lastClick < 400) ? Math.min(this._clickCount + 1, 3) : 1
  346. this._lastClick = now
  347. var p = this.#point(event)
  348. this.#send({
  349. t: 'mouse', action: 'down', x: p.x, y: p.y,
  350. button: event.button === 2 ? 'right' : event.button === 1 ? 'middle' : 'left',
  351. buttons: event.buttons, clickCount: this._clickCount, modifiers: mods(event)
  352. })
  353. try { canvas.setPointerCapture(event.pointerId) } catch (err) { /* 合成事件没有指针 */ }
  354. })
  355. canvas.addEventListener('pointermove', (event) => {
  356. if (this._movePending) return
  357. this._movePending = true
  358. var p = this.#point(event)
  359. requestAnimationFrame(() => {
  360. self._movePending = false
  361. self.#send({
  362. t: 'mouse', action: 'move', x: p.x, y: p.y,
  363. buttons: event.buttons, modifiers: mods(event)
  364. })
  365. })
  366. })
  367. canvas.addEventListener('pointerup', (event) => {
  368. event.preventDefault()
  369. var p = this.#point(event)
  370. this.#send({
  371. t: 'mouse', action: 'up', x: p.x, y: p.y,
  372. button: event.button === 2 ? 'right' : event.button === 1 ? 'middle' : 'left',
  373. buttons: event.buttons, clickCount: this._clickCount, modifiers: mods(event)
  374. })
  375. })
  376. canvas.addEventListener('wheel', (event) => {
  377. event.preventDefault()
  378. var p = this.#point(event)
  379. this.#send({
  380. t: 'mouse', action: 'wheel', x: p.x, y: p.y,
  381. deltaX: Math.round(event.deltaX), deltaY: Math.round(event.deltaY), modifiers: mods(event)
  382. })
  383. }, { passive: false })
  384. canvas.addEventListener('contextmenu', (event) => event.preventDefault())
  385. sink.addEventListener('keydown', (event) => {
  386. var key = event.key
  387. var printable = key && key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey
  388. if (printable) return // 交给 input 事件(含输入法)
  389. if (!SPECIAL_KEYS[key] && !/^F\d{1,2}$/.test(key) && !(event.ctrlKey || event.metaKey)) return
  390. event.preventDefault()
  391. this.#send({
  392. t: 'key', action: 'down', key: key, code: event.code,
  393. keyCode: event.keyCode, modifiers: mods(event), repeat: event.repeat
  394. })
  395. this.#send({ t: 'key', action: 'up', key: key, code: event.code, keyCode: event.keyCode, modifiers: mods(event) })
  396. })
  397. sink.addEventListener('input', () => {
  398. var text = sink.value
  399. if (!text) return
  400. sink.value = ''
  401. this.#send({ t: 'text', text: text })
  402. })
  403. sink.addEventListener('compositionend', () => {
  404. var text = sink.value
  405. if (!text) return
  406. sink.value = ''
  407. this.#send({ t: 'text', text: text })
  408. })
  409. sink.addEventListener('paste', (event) => {
  410. event.preventDefault()
  411. var text = (event.clipboardData || window.clipboardData).getData('text')
  412. if (text) this.#send({ t: 'text', text: text })
  413. })
  414. }
  415. }
  416. try {
  417. window.customElements.define('webview', CocoWebview)
  418. } catch (err) { /* 已定义(页面被重复注入) */ }
  419. /**
  420. * 给 shim 用的页签登记表。
  421. * 桌面端"复用右侧页签"是主进程去挑 webview;这里挑的是 DOM 里的同名元素。
  422. */
  423. window.__ccWebviews = {
  424. elements: [],
  425. open: function (url) {
  426. var host = hostOf(url)
  427. var all = document.querySelectorAll('webview')
  428. for (var i = 0; i < all.length; i += 1) {
  429. if (hostOf(all[i].getURL ? all[i].getURL() : all[i].src) === host) {
  430. all[i].loadURL(url)
  431. return Promise.resolve({ ok: true, reused: true })
  432. }
  433. }
  434. return Promise.resolve({ ok: false, error: 'no-dock' })
  435. }
  436. }
  437. })()