阿里妹导读:如今微前端已经成为前端领域比较火爆的话题,在技术方面,微前端有一个始终绕不过去的话题就是前端沙箱。本文将分享阿里云开放平台微前端方案的沙箱实现原理,具体探讨在微前端领域如何实现前端沙箱。
文末福利:下载《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 app
aliyun-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'
// 销毁一个 context
await 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$/,
}
联系客服