当前位置: 首页 > Web前端 > JavaScript

沙盒机制沙盒

时间:2023-03-26 20:46:20 JavaScript

最近手头的项目应用了沙盒机制。顺便直接研究了一下代码~functionsandbox(code){code='with(sandbox){'+code+'}'returnnewFunction('sandbox',code)}letstr='leta=10;console.log(a)'sandbox(str)({})//es6proxy可以解决这个问题,proxy可以设置访问拦截器,所以加上proxy几乎可以完美解决js沙箱机制。当然,还是有可以绕过的机制的。有高手发现Symbol.unScopables不能被with影响,所以Symbol.unScopables要单独处理:(target,prop,value){target[prop]=value返回true},get(target,prop){returntarget[prop]||fakeWindow[prop]}})this.proxy=proxy}}constsandbox1=newProxySandbox()constsandbox2=newProxySandbox()window.a=1((window)=>{window.a='hello'console.log(window.a)})(sandbox1.proxy)((window)=>{window.a='world'console.log(window.a)})(sandbox1.proxy)上面的例子是应用于es6proxy,目前jssandbox能做的最好的沙盒box机制适合多种应用程序,但也有兼容性限制。快照沙箱类snapShotSandbox{proxy=window//窗口属性modifyPropsMap={}//记录在窗口上的MODIFYactive()active(){//rageboxthis.windowSnapshot={}//beatfor(constpropinwindow){if(window.hasOwnProperty(prop)){this.windowSnapshot[prop]=window[prop]}}Object.keys(this.modifyPropsMap).forEach(prop=>{window[prop]=this.modifyPropsMap[prop]})}inactive(){//Inactiveboxfor(constpropinwindow){if(window.hasOwnProperty(prop)){if(window[prop]!==this.windowSnapshot[prop]){this.modifyPropsMap[prop]=window[prop]window[prop]=this.windowSnapshot[prop]}}}}constsandbox=newsnapShotSandbox()((window)=>{window.a=1window.b=2console.log(窗口.a,window.b)sandbox.inactive()console.log(window.a,window.b)sandbox.active()console.log(window.a,window.b)})(sandbox.proxy)//sandbox.proxy应该是window//不支持多应用