分享一道今天面试遇到的面试题,前端开发相关

2 月 25 日
 Zhuzhuchenyan

给定一个 host.html

<!doctype html>
<meta charset="utf-8" />
<title>host</title>

<iframe
  id="outer"
  sandbox="allow-scripts"
  src="https://another-site/sandbox.html"
></iframe>

其中 sandbox.html

<!doctype html>
<meta charset="utf-8" />
<title>sandbox</title>

<script>
  const inner = document.createElement('iframe');
  inner.src = 'https://another-another-site/inner.html';
  document.body.appendChild(inner);
</script>

其中 inner.html

<!doctype html>
<meta charset="utf-8" />
<title>inner</title>

<script>
    const v = localStorage.getItem('no_such_key');
    console.log('value:', v);
</script>

问:试分析localStorage.getItem('no_such_key')的行为


我的回答:这大概率会抛出一个 SecurityError ,我的映像里因为 sandbox 的缘故 iframe 里面的网页浏览器是不会指定 origin 的。没有 origin 的话大概率 localstorage, session storage, index db 这一类都不可用

Follow up

  1. iframe src 和 iframe origin 的关系
  2. sandbox 里哪个属性控制这个行为?
  3. 在 inner html 里类似 fetch(..., { credentials: "include" })请求在哪些情况会带上 cookie
2747 次点击
所在节点    程序员
6 条回复
susunus
2 月 26 日
你面试的是安全相关还是简历有这方面的说明,总之我感觉这个问题有点傻逼,平时完全用不上的冷门知识点拿来考
GreatAuk
2 月 26 日
好偏门啊,但现在有 ai 了,一问一个准...
xiaowoli
2 月 26 日
考这么细的 API 有什么用呢?能让写代码的时候少看两分钟的文档吗?
toyst
2 月 26 日
现在有 AI 了,题都懒得看完,直接复制粘贴给 AI
notproblem
2 月 26 日
实际测试了:
1. sandbox.html 获取 body 会报错,因为 body 标签没有;
2. 子 iframe 的 sandbox 属性没有设置,会等于父 iframe 的 sandbox 设置,也就是只有 allow-scripts ,没有 allow-same-origin 。所以会无法访问 localStorage,直接报错。如果子 iframe 设置了 sandbox ,会和父 iframe 的 sandbox 属性取交集,得到最小的允许的权限。
HeyWeGo
2 月 26 日
没接触过,我会问 AI ,并且手动验证下。反问业务上这种情况多吗?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1194098

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX