Hook Vue3 app

通过劫持Proxy方法,逆向还原Vue3 app元素到DOM

目前為 2022-08-13 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/449444/1080975/Hook%20Vue3%20app.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Hook Vue3 app
// @version      1.0.2
// @description  通过劫持Proxy方法,逆向还原Vue3 app元素到DOM
// @author       DreamNya
// @license      MIT
// @namespace https://greasyfork.org/users/809466
// ==/UserScript==

const $window = window.unsafeWindow || document.defaultView || window
const realLog = $window.console.log; //反劫持console.log
const realProxy = $window.Proxy; //劫持Proxy

var vueApp = {} //存储所有app
var vueHooked = {} //存储已还原app

$window.Proxy = function () {
    let app = arguments[0]._
    if (app && app.uid >= 0) { //判断app
        let el = app.vnode.el
        if (el) {
            if (!el.__vue__) {
                el.__vue__ = app //存在el则还原__vue__
                if (el.__vue__) {
                    recordVue(vueHooked, app)
                }
            }
        } else {
            //realLog(app,el)
            watchEl(app.vnode) //不存在el则进行观察
        }
        recordVue(vueApp, app)
    }
    return new realProxy(...arguments)
}

function watchEl(vnode) { //观察el 变动时还原到DOM
    let value = vnode.el
    let hooked = false
    Object.defineProperty(vnode, "el", {
        get() {
            return value
        },
        set(newValue) {
            value = newValue
            if (!hooked && this.el) {
                this.el.__vue__ = this.component
                if (this.el.__vue__) {
                    hooked = true
                    recordVue(vueHooked, this.component)
                    //realLog(this.component,"已还原")
                }
            }
        }
    })
}

function recordVue(obj, app) { //以uid为key存储app
    if (!obj[app.uid]) { //uid不存在则直接存储
        obj[app.uid] = app
    } else if (Array.isArray(obj[app.uid])) {
        obj[app.uid].push(app)
    } else {
        obj[app.uid] = [obj[app.uid], app] //多个root相同uid时以数组形式存储 可能存在优化空间
    }
}