Secure Context - 安全上下文
在 window 或 worker 中使用一些涉及 用户隐私、一些数据访问或计算机的低级访问权限等相关 API 时,为了防止 中间人攻击者 访问这些接口,从而限制需要在 安全上下文 中使用。
上下文在什么情况下是安全的?
本地资源:
http://127.0.0.1、http://localhost、http://*.localhost或file://协议的资源是安全的非本地资源:通过
TLS传输的,例如https://或wss://协议的资源是安全的
使用 window 和 worker 属性来判断当前是否在安全上下文中
if (window.isSecureContext) {
// 页面在安全上下文中,所以 service worker 可用
navigator.serviceWorker.register("/offline-worker.js").then(() => {
// …
});
}
解决 Secure Context 限制
使用 Https 协议
一般情况下,使用 localhost 或 127.0.0.1 等本地测试时,是处于 安全上下文中 的,由于某些测试环境,可能需要域名访问等场景,使用例如 clipboard、Crypto 等 API 时则会出现 安全上下文 限制。
Chrome 中关闭 Secure Context 的限制
前后对比
[{"url":"https://static.ksh7.com/post/js-secure-context-UUID/0085UwQ9ly1htk8nvm9etj32460kegzu.webp?imageMogr2/thumbnail/!50p","dataset":{"originPic":"https://static.ksh7.com/post/js-secure-context-UUID/0085UwQ9ly1htk8nvm9etj32460kegzu.webp","thumbnail":""}},{"url":"https://static.ksh7.com/post/js-secure-context-UUID/0085UwQ9ly1htk8nuytu8j326s0e0n9e.webp?imageMogr2/thumbnail/!50p","dataset":{"originPic":"https://static.ksh7.com/post/js-secure-context-UUID/0085UwQ9ly1htk8nuytu8j326s0e0n9e.webp","thumbnail":""}}]
























