daily-share icon indicating copy to clipboard operation
daily-share copied to clipboard

实现快照沙箱(2021-2-7)

Open yaogengzhu opened this issue 4 years ago • 0 comments

实现快照沙箱

// 沙箱就是互不影响,创造一个干净的环境, 当切换时,可以选择丢弃属性或恢复属性
        // js沙箱 proxy
        // 快照沙箱   将区别保存起来
        class SnpashotSandBox {
            constructor() {
                this.proxy = window
                this.modifyPropsMap = {}
                this.active()
            }

            active() {
                this.windowSnpashot = {} // 拍照
                for (const prop in window) {
                    if (window.hasOwnProperty(prop)) {
                        this.windowSnpashot[prop] = window[prop]
                    }
                }

                Object.keys(this.modifyPropsMap).forEach(p => {
                    window[p] = this.modifyPropsMap[p]
                })
            }
            inactive() {
                for (const prop in window) {
                    if (window.hasOwnProperty(prop)) {
                        if (window[prop] !== this.windowSnpashot[prop]) {
                            this.modifyPropsMap[prop] = window[prop]
                            window[prop] = this.windowSnpashot[prop]
                        }
                    }
                }
            }


        }
        let sandBox = new SnpashotSandBox();

        ((window) => {
            window.a = 1
            window.b = 2

            console.log(window.a, window.b)

            sandBox.inactive()

            console.log(window.a, window.b)

            sandBox.active()
            console.log(window.a, window.b)
        })(sandBox.proxy)

        // 如果时多个子应用就不能这个这种方式了
        // 代理沙箱可以实现多个应用沙箱

yaogengzhu avatar Feb 06 '21 16:02 yaogengzhu