惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
Stack Overflow Blog
Stack Overflow Blog
量子位
腾讯CDC
N
Netflix TechBlog - Medium
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
S
SegmentFault 最新的问题
A
About on SuperTechFans
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
G
Google Developers Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
罗磊的独立博客
Vercel News
Vercel News
L
LangChain Blog
V
V2EX
P
Proofpoint News Feed
M
MIT News - Artificial intelligence
博客园 - Franky
V
Visual Studio Blog
J
Java Code Geeks

时间的朋友

Windows 命令行密码重置 Anaconda安装 typescript 注解解读1 Konvajs Shape加载自定义图片 sshpass 使用 why-is-node-running webgl笔记 SharedArrayBuffer is not defined blender 常用快捷键 | 时间的朋友 vue -- v3.4commit提交记录2 vue2 升级vue3报错问题整理 着色器 expressjs 源码 hyper-V arch linux 网络配置 element input数字格式化 three 拼接货架 WebAudio笔记 Windows nginx重启bat脚本 vue -- v3.4commit提交记录 URI malformed vue3 -- Class 对象在组件中使用范例 | 时间的朋友 ruby 安装和升级 element-plus 老版本cascader使用卡死问题 vue3 内置Transition组件 | 时间的朋友 前端memo的实现 | 时间的朋友 Vue -- vue-class-component源码 | 时间的朋友 linux 优化脚本 typescript 装饰器 | 时间的朋友 microbundle 源码 | 时间的朋友 WSL2问题解决WslRegisterDistribution failed with error: 0x800701bc
import-html-entry js沙箱实现源码 | 时间的朋友
2023-03-15 · via 时间的朋友

Published: · LastMod: March 16, 2023 · 499 words

import-html-entry js沙箱实现 🔗

getExecutableScript函数 🔗

  • scriptText: 读取js文件的内容
  • sourceUrl:用作sourcemap的指引
1
2
3
4
5
;(function(window, self, globalThis){
	// scriptText
	 // sourceUrl
	})
.bind(window.proxy)(window.proxy, window.proxy, window.proxy);

内部实现其实就是拼接了一个自执行函数,最后使用eval执行该字符串达到函数执行的目的

仔细分析这个沙箱函数

  • 第一步,声明一个函数,并且把代码放入函数内部执行,这里通过函数内部的作用域进行隔离
  • 第二步: 通过bind函数改变上下文作用域window.proxy
  • 第三步:执行该函数,传入三个参数window.proxy

这样函数体内部的window,其实是外部参数传入的window

为防止嵌套应用内部拿到的window执行错误问题

1
2
3
4
// 通过这种方式获取全局 window,因为 script 也是在全局作用域下运行的,所以我们通过 window.proxy 绑定时也必须确保绑定到全局 window 上
	// 否则在嵌套场景下, window.proxy 设置的是内层应用的 window,而代码其实是在全局作用域运行的,会导致闭包里的 window.proxy 取的是最外层的微应用的 proxy
const globalWindow = (0, eval)('window');
globalWindow.proxy = proxy;

代码注释写的很明白

通过eval('window')拿到全局window

Reference 🔗

https://juejin.cn/post/7184419253087535165

https://juejin.cn/post/7148075486403362846