阿里妹导读:如今微前端已经成为前端领域比较火爆的话题,在技术方面,微前端有一个始终绕不过去的话题就是前端沙箱。本文将分享阿里云开放平台微前端方案的沙箱实现原理,具体探讨在微前端领域如何实现前端沙箱。
文末福利:下载《2020 前端工程师必读手册》电子书。
function foo(window) { console.log(window.document);}foo({ document: {};});
// 打包代码__CONSOLE_OS_GLOBAL_HOOK__(id, function (require, module, exports, {window, document, location, history}) { /* 打包代码 */})function __CONSOLE_OS_GLOBAL_HOOK__(id, entry) { entry(require, module, exports, {window, document, location, history})}
const iframe = document.createElement( 'iframe' );
class Window { constructor(options, context, frame) { return new Proxy(frame.contentWindow, { set(target, name, value) { target[name] = value; return true; }, get(target, name) { switch( name ) { case 'document': return context.document; default: } if( typeof target[ name ] === 'function' && /^[a-z]/.test( name ) ){ return target[ name ].bind && target[ name ].bind( target ); }else{ return target[ name ]; } } }); }}
// 宿主 host app.next-btn { color: #eee;}// 子应用 sub appaliyun-slb .next-btn { color: #eee;}//宿主中生成的节点<aliyun-slb> <!-- 子应用的节点 --></aliyun-slb>
import { createContext, removeContext } from '@alicloud/console-os-browser-vm';const context = await createContext();const run = window.eval(` (() => function({window, history, locaiton, document}) { window.test = 1; })()`)run(context);console.log(context.window.test);console.log(window.test);// 操作虚拟化浏览器对象context.history.pushState(null, null, '/test');context.locaiton.hash = 'foo'// 销毁一个 contextawait removeContext( context );
import { evalScripts } from '@alicloud/console-os-browser-vm';const context = evalScripts('window.test = 1;')console.log(window.test === undefined) // true
const postcssWrap = require('@alicloud/console-toolkit-plugin-os/lib/postcssWrap')// 下面是 webpack config{ test: /\.css$/, use: [ 'style-loader', { loader: 'postcss-loader', options: { plugins: [ // 加入插件 postcssWrap({ stackableRoot: '.prefix', repeat: 1 }) ], }, }, 'css-loader', ], exclude: /^node_modules$/,}
《2020 前端工程师必读手册》
阿里巴巴前端委员会推荐!覆盖语言框架、前端智能化、微前端、Serverless 及工程化 5 大热点前端技术方向、10+ 核心实战的前端手册,解锁前端新方式,挖掘前端新思路,尽在此刻,赶紧来先睹为快!
推荐阅读