在 HTML 文件中加载 JavaScript 会在本地环境中仅针对 ES6 模块而不是旧 JS 引发跨源请求错误,为什么?

Loading JavaScript in HTML files throws a cross origin request error in local environment only for ES6 modules and not for old JS, why?

我有这三个文件:

script.js

alert("script")

module.mjs

alert("module")

和index.html

<script src="./script.js"></script>
<script src="./module.mjs" type="module"></script>

没有服务器是 运行。

如果我打开浏览器并导航到我的本地 index.html 文件,我可以看到正在显示脚本警报,但该模块被跨源策略阻止。

Chrome 和 Firefox 都表现出相同的行为,但我正在从我的本地环境访问所有文件,所以为什么他们说在一种情况下存在跨源策略违规,而在另一种情况下却没有?

可以找到部分原因但在我的情况下加载了script.js,为什么跨源策略仅适用于ES6模块?

支持不带 CORS 的非模块的跨源脚本加载是一项向后兼容的遗留功能。

来自 discussion 在规范开发过程中:

The web's fundamental security model is the same origin policy. We have several legacy exceptions to that rule from before that security model was in place, with script tags being one of the most egregious and most dangerous. (See the various "JSONP" attacks.)

Many years ago, perhaps with the introduction of XHR or web fonts (I can't recall precisely), we drew a line in the sand, and said no new web platform features would break the same origin policy. The existing features need to be grandfathered in and subject to carefully-honed and oft-exploited exceptions, for the sake of not breaking the web, but we certainly can't add any more holes to our security policy.

That's why, from our perspective, making module scripts bypass the CORS protocol (and thus the same-origin policy) is a non-starter. It's not about a specific attack scenario, apart from the ones already enabled by classic scripts; it's about making sure that new features added to the platform don't also suffer from the past's bad security hygiene.