| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494 |
- /**
- * <webview> 的 Web 实现
- * ====================
- * 品牌插件(client.js)用 `document.createElement("webview")` 挂右侧平台页面,
- * 这是 Electron 专有标签,普通浏览器里没有。这个文件把它补成一个自定义元素:
- *
- * 元素 = 一块 canvas(画服务端 Chromium 的画面)+ 一个隐藏输入框(接键盘/输入法)
- * 属性 = src / partition / name 全部接受,值不参与逻辑(partition 是 Electron 会话概念)
- * 方法 = loadURL / reload / getURL / openDevTools
- * 事件 = did-start-loading / did-stop-loading / page-title-updated / did-fail-load
- *
- * 关键行为:**从 DOM 上摘下来再挂回去不重新加载**。
- * 桌面端为此专门把 webview 提成模块级单例(切会话时只是 detach),Web 版靠服务端
- * 页签常驻来实现同样的语义:attach 只重连画面,不导航。
- */
- (function () {
- 'use strict'
- if (window.customElements && window.customElements.get('webview')) return
- var WS = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/_cc/rt?tab='
- /**
- * API 模式:服务端不代理浏览器,右侧栏没有画面可接。
- * 这时 <webview> 降级成一张卡片 —— 地址交给老师自己的浏览器打开
- * (同域,登录态在老师本机),元素的方法与事件仍然照常触发,
- * 品牌插件那侧不需要改一行。
- */
- var EXTERNAL = !!(window.__CC__ && window.__CC__.pageMode && window.__CC__.pageMode !== 'browser')
- function hostOf (url) {
- try { return new URL(url).host } catch (err) { return '' }
- }
- function post (path, body) {
- return fetch(location.origin + path, {
- method: 'POST',
- credentials: 'same-origin',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(body || {})
- }).then(function (res) { return res.json() })
- }
- function emit (el, type, props) {
- var event = new Event(type)
- if (props) Object.assign(event, props)
- el.dispatchEvent(event)
- }
- function mods (event) {
- return (event.shiftKey ? 1 : 0) | (event.altKey ? 1 << 1 : 0) | (event.ctrlKey ? 1 << 2 : 0) | (event.metaKey ? 1 << 3 : 0)
- }
- var SPECIAL_KEYS = {
- Enter: 1, Tab: 1, Escape: 1, Backspace: 1, Delete: 1, ArrowUp: 1, ArrowDown: 1,
- ArrowLeft: 1, ArrowRight: 1, Home: 1, End: 1, PageUp: 1, PageDown: 1
- }
- class CocoWebview extends HTMLElement {
- constructor () {
- super()
- this._url = ''
- this._tabId = ''
- this._ws = null
- this._retry = 0
- this._timer = null
- this._attaching = null
- this._lastClick = 0
- this._clickCount = 1
- this._pendingFrame = false
- this._lastSize = { w: 0, h: 0 }
- this._observer = null
- this._built = false
- }
- // ---------------------------------------------------------------- DOM
- #build () {
- if (this._built) return
- this._built = true
- if (EXTERNAL) return this.#buildCard()
- var wrap = document.createElement('div')
- wrap.style.cssText = 'position:relative;flex:1;width:100%;height:100%;overflow:hidden;background:#fff;'
- var canvas = document.createElement('canvas')
- canvas.style.cssText = 'width:100%;height:100%;display:block;touch-action:none;cursor:default;outline:none;'
- canvas.width = 1280
- canvas.height = 800
- // 键盘接这里:真实输入框才能唤起输入法候选窗,也能拿到粘贴
- var sink = document.createElement('textarea')
- sink.setAttribute('autocomplete', 'off')
- sink.setAttribute('autocorrect', 'off')
- sink.setAttribute('autocapitalize', 'off')
- sink.setAttribute('spellcheck', 'false')
- sink.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;' +
- 'border:0;padding:0;resize:none;overflow:hidden;z-index:1;'
- wrap.appendChild(canvas)
- wrap.appendChild(sink)
- this.appendChild(wrap)
- this.style.display = this.style.display || 'flex'
- this._canvas = canvas
- this._ctx = canvas.getContext('2d', { alpha: false })
- this._sink = sink
- this._bind()
- }
- /** API 模式的呈现:没有画面,只有一个"去浏览器打开"的入口 */
- #buildCard () {
- var wrap = document.createElement('div')
- wrap.style.cssText = 'flex:1;width:100%;height:100%;display:flex;align-items:center;' +
- 'justify-content:center;background:#f7f8fa;'
- var card = document.createElement('div')
- card.style.cssText = 'max-width:420px;text-align:center;padding:28px 24px;border:1px solid #e5e6eb;' +
- 'border-radius:12px;background:#fff;box-shadow:0 2px 8px rgba(0,0,0,.04);'
- var title = document.createElement('div')
- title.style.cssText = 'font:600 15px/1.5 -apple-system,"Segoe UI",system-ui,"PingFang SC",sans-serif;' +
- 'color:#1d2129;margin-bottom:8px;word-break:break-all;'
- title.textContent = '平台页面'
- var desc = document.createElement('div')
- desc.style.cssText = 'font:13px/1.7 -apple-system,"Segoe UI",system-ui,"PingFang SC",sans-serif;' +
- 'color:#86909c;margin-bottom:16px;'
- desc.textContent = '本次部署不代理浏览器。点下面的按钮,在你自己浏览器的标签页里打开,登录态和平时一致。'
- var btn = document.createElement('a')
- btn.target = '_blank'
- btn.rel = 'noopener noreferrer'
- btn.textContent = '在浏览器打开'
- btn.style.cssText = 'display:inline-block;padding:8px 18px;border-radius:8px;background:#165DFF;' +
- 'color:#fff;text-decoration:none;font:500 14px/1.4 -apple-system,"Segoe UI",system-ui,sans-serif;'
- btn.addEventListener('click', () => {
- // 老师主动点了才算"打开成功":把插件的 loading 态收尾,避免右侧栏一直转圈
- emit(this, 'page-title-updated', { title: hostOf(this._url) })
- emit(this, 'did-stop-loading')
- })
- card.appendChild(title)
- card.appendChild(desc)
- card.appendChild(btn)
- wrap.appendChild(card)
- this.appendChild(wrap)
- this.style.display = this.style.display || 'flex'
- this._cardTitle = title
- this._cardDesc = desc
- this._cardBtn = btn
- this.#updateCard()
- }
- #updateCard () {
- if (!this._cardBtn) return
- var url = this._url || ''
- this._cardBtn.href = url || '#'
- this._cardBtn.style.opacity = url ? '1' : '.45'
- this._cardBtn.style.pointerEvents = url ? 'auto' : 'none'
- if (url) {
- this._cardTitle.textContent = hostOf(url) || '平台页面'
- this._cardDesc.textContent =
- '本次部署不代理浏览器。点下面的按钮,在你自己浏览器的标签页里打开,登录态和平时一致。'
- }
- }
- connectedCallback () {
- this.#build()
- if (this._url) this.#attach(this._url)
- this.#observeSize()
- }
- disconnectedCallback () {
- // 只断开画面传输,不动服务端页签:挂回来还是原来那一页
- this.#closeSocket()
- if (this._observer) { this._observer.disconnect(); this._observer = null }
- }
- attributeChangedCallback (name, oldValue, value) {
- if (name === 'src' && value && value !== oldValue) this.loadURL(value)
- }
- static get observedAttributes () { return ['src'] }
- get src () { return this._url }
- set src (value) { this.loadURL(value) }
- getURL () { return this._url }
- // ---------------------------------------------------------------- 导航
- /** 明确要求换地址(桌面端"目标变了才导航"的语义) */
- loadURL (url) {
- var target = String(url || '').trim()
- if (!/^https?:\/\//i.test(target)) return Promise.resolve({ ok: false, error: 'bad-url' })
- this._url = target
- emit(this, 'did-start-loading')
- if (EXTERNAL) {
- this.#build()
- this.#updateCard()
- // 没有真的在加载,但插件在 did-stop-loading 里收尾,必须给一次
- setTimeout(() => {
- emit(this, 'page-title-updated', { title: hostOf(target) })
- emit(this, 'did-stop-loading')
- }, 0)
- return Promise.resolve({ ok: true, mode: 'external', url: target })
- }
- return post('/_cc/api/browser/open', { url: target })
- .then((res) => {
- if (!res || !res.ok) {
- emit(this, 'did-fail-load', { errorDescription: (res && res.error) || 'open-failed', isMainFrame: true })
- return res || { ok: false }
- }
- this._tabId = res.tabId
- this._retry = 0
- this.#connect()
- return res
- })
- .catch((err) => {
- emit(this, 'did-fail-load', { errorDescription: err.message, isMainFrame: true })
- return { ok: false, error: err.message }
- })
- }
- /** 挂回 DOM 时用:有同站页签就接上,没有才新建(绝不因为"切会话"刷新页面) */
- #attach (url) {
- if (EXTERNAL) {
- // 没有服务端页签可接,地址留着给卡片按钮用
- if (!this._url && url) this._url = String(url)
- this.#build()
- this.#updateCard()
- return Promise.resolve(null)
- }
- if (this._attaching) return this._attaching
- this._attaching = post('/_cc/api/browser/attach', { url })
- .then((res) => {
- this._attaching = null
- if (!res || !res.ok) return null
- this._tabId = res.tabId
- if (res.url) this._url = res.url
- this.#connect()
- return res
- })
- .catch(() => { this._attaching = null; return null })
- return this._attaching
- }
- reload () {
- if (EXTERNAL) {
- // 刷新的是老师自己浏览器里的标签,这里只做状态回放
- emit(this, 'did-start-loading')
- setTimeout(() => emit(this, 'did-stop-loading'), 0)
- return Promise.resolve({ ok: true, mode: 'external' })
- }
- return post('/_cc/api/browser/reload', { tabId: this._tabId, hard: false })
- }
- openDevTools () { /* headless 里没有 F12;控制台走右侧面板的日志条 */ }
- // ---------------------------------------------------------------- 连接
- #connect () {
- if (EXTERNAL) return
- if (!this._tabId) return
- if (this._ws && this._ws.readyState <= 1 && this._ws._tabId === this._tabId) return
- this.#closeSocket()
- var ws
- try { ws = new WebSocket(WS + encodeURIComponent(this._tabId)) } catch (err) { return this.#scheduleRetry() }
- ws.binaryType = 'blob'
- ws._tabId = this._tabId
- this._ws = ws
- ws.onopen = () => {
- this._retry = 0
- // 尺寸先发过去:服务端按这个尺寸设视口,画面才和画布一样大
- this.#sendSize(true)
- }
- ws.onmessage = (event) => {
- if (typeof event.data === 'string') {
- this.#control(event.data)
- return
- }
- this.#frame(event.data)
- }
- ws.onclose = () => {
- if (this._ws === ws) this._ws = null
- if (this.isConnected) this.#scheduleRetry()
- }
- ws.onerror = () => { /* onclose 会跟着来 */ }
- }
- #closeSocket () {
- var ws = this._ws
- this._ws = null
- if (ws) { try { ws.close() } catch (err) { /* 已经关了 */ } }
- }
- #scheduleRetry () {
- if (this._timer) return
- var delay = Math.min(800 * Math.pow(1.6, this._retry++), 8000)
- this._timer = setTimeout(() => {
- this._timer = null
- if (this.isConnected) this.#connect()
- }, delay)
- }
- #control (raw) {
- var msg = null
- try { msg = JSON.parse(raw) } catch (err) { return }
- if (msg.t === 'state') {
- if (msg.field === 'title') emit(this, 'page-title-updated', { title: msg.value })
- else if (msg.field === 'loading') emit(this, msg.value ? 'did-start-loading' : 'did-stop-loading')
- else if (msg.field === 'error') {
- emit(this, 'did-fail-load', { errorDescription: msg.value, isMainFrame: true })
- } else if (msg.field === 'url' && msg.value) {
- this._url = msg.value
- }
- return
- }
- if (msg.t === 'log') {
- this.__ccLogs = this.__ccLogs || []
- this.__ccLogs.push(msg)
- if (this.__ccLogs.length > 200) this.__ccLogs.shift()
- this.dispatchEvent(new CustomEvent('cc-log', { detail: msg }))
- }
- }
- #frame (blob) {
- if (this._pendingFrame) return // 上一帧还没画完,丢掉这一帧(画面不会因此滞后)
- this._pendingFrame = true
- var self = this
- createImageBitmap(blob).then(function (bmp) {
- var canvas = self._canvas
- if (!canvas || !self._ctx) { bmp.close && bmp.close(); return }
- if (canvas.width !== bmp.width || canvas.height !== bmp.height) {
- canvas.width = bmp.width
- canvas.height = bmp.height
- }
- self._ctx.drawImage(bmp, 0, 0)
- bmp.close && bmp.close()
- }).catch(function () { /* 半帧/坏帧,跳过 */ }).then(function () {
- self._pendingFrame = false
- })
- }
- // ---------------------------------------------------------------- 尺寸
- #observeSize () {
- if (this._observer || typeof ResizeObserver === 'undefined') return
- this._observer = new ResizeObserver(() => this.#sendSize(false))
- this._observer.observe(this)
- this.#sendSize(true)
- }
- #sendSize (force) {
- var rect = this.getBoundingClientRect()
- var w = Math.round(rect.width)
- var h = Math.round(rect.height)
- if (w < 50 || h < 50) return
- if (!force && Math.abs(w - this._lastSize.w) < 8 && Math.abs(h - this._lastSize.h) < 8) return
- this._lastSize = { w: w, h: h }
- this.#send({ t: 'resize', w: w, h: h })
- }
- // ---------------------------------------------------------------- 输入
- #send (msg) {
- var ws = this._ws
- if (ws && ws.readyState === 1) {
- try { ws.send(JSON.stringify(msg)) } catch (err) { /* 连接刚断 */ }
- }
- }
- #point (event) {
- var rect = this._canvas.getBoundingClientRect()
- var scaleX = this._canvas.width / Math.max(rect.width, 1)
- var scaleY = this._canvas.height / Math.max(rect.height, 1)
- return {
- x: Math.round((event.clientX - rect.left) * scaleX),
- y: Math.round((event.clientY - rect.top) * scaleY)
- }
- }
- #bind () {
- var canvas = this._canvas
- var sink = this._sink
- var self = this
- canvas.addEventListener('pointerdown', (event) => {
- event.preventDefault()
- sink.focus({ preventScroll: true })
- var now = Date.now()
- this._clickCount = (now - this._lastClick < 400) ? Math.min(this._clickCount + 1, 3) : 1
- this._lastClick = now
- var p = this.#point(event)
- this.#send({
- t: 'mouse', action: 'down', x: p.x, y: p.y,
- button: event.button === 2 ? 'right' : event.button === 1 ? 'middle' : 'left',
- buttons: event.buttons, clickCount: this._clickCount, modifiers: mods(event)
- })
- try { canvas.setPointerCapture(event.pointerId) } catch (err) { /* 合成事件没有指针 */ }
- })
- canvas.addEventListener('pointermove', (event) => {
- if (this._movePending) return
- this._movePending = true
- var p = this.#point(event)
- requestAnimationFrame(() => {
- self._movePending = false
- self.#send({
- t: 'mouse', action: 'move', x: p.x, y: p.y,
- buttons: event.buttons, modifiers: mods(event)
- })
- })
- })
- canvas.addEventListener('pointerup', (event) => {
- event.preventDefault()
- var p = this.#point(event)
- this.#send({
- t: 'mouse', action: 'up', x: p.x, y: p.y,
- button: event.button === 2 ? 'right' : event.button === 1 ? 'middle' : 'left',
- buttons: event.buttons, clickCount: this._clickCount, modifiers: mods(event)
- })
- })
- canvas.addEventListener('wheel', (event) => {
- event.preventDefault()
- var p = this.#point(event)
- this.#send({
- t: 'mouse', action: 'wheel', x: p.x, y: p.y,
- deltaX: Math.round(event.deltaX), deltaY: Math.round(event.deltaY), modifiers: mods(event)
- })
- }, { passive: false })
- canvas.addEventListener('contextmenu', (event) => event.preventDefault())
- sink.addEventListener('keydown', (event) => {
- var key = event.key
- var printable = key && key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey
- if (printable) return // 交给 input 事件(含输入法)
- if (!SPECIAL_KEYS[key] && !/^F\d{1,2}$/.test(key) && !(event.ctrlKey || event.metaKey)) return
- event.preventDefault()
- this.#send({
- t: 'key', action: 'down', key: key, code: event.code,
- keyCode: event.keyCode, modifiers: mods(event), repeat: event.repeat
- })
- this.#send({ t: 'key', action: 'up', key: key, code: event.code, keyCode: event.keyCode, modifiers: mods(event) })
- })
- sink.addEventListener('input', () => {
- var text = sink.value
- if (!text) return
- sink.value = ''
- this.#send({ t: 'text', text: text })
- })
- sink.addEventListener('compositionend', () => {
- var text = sink.value
- if (!text) return
- sink.value = ''
- this.#send({ t: 'text', text: text })
- })
- sink.addEventListener('paste', (event) => {
- event.preventDefault()
- var text = (event.clipboardData || window.clipboardData).getData('text')
- if (text) this.#send({ t: 'text', text: text })
- })
- }
- }
- try {
- window.customElements.define('webview', CocoWebview)
- } catch (err) { /* 已定义(页面被重复注入) */ }
- /**
- * 给 shim 用的页签登记表。
- * 桌面端"复用右侧页签"是主进程去挑 webview;这里挑的是 DOM 里的同名元素。
- */
- window.__ccWebviews = {
- elements: [],
- open: function (url) {
- var host = hostOf(url)
- var all = document.querySelectorAll('webview')
- for (var i = 0; i < all.length; i += 1) {
- if (hostOf(all[i].getURL ? all[i].getURL() : all[i].src) === host) {
- all[i].loadURL(url)
- return Promise.resolve({ ok: true, reused: true })
- }
- }
- return Promise.resolve({ ok: false, error: 'no-dock' })
- }
- }
- })()
|