简短版
是否可以在脚本的外来源下创建一个indexedDB,通过importScripts()导入?
长版
我的目标是能够通过共享服务工作者跨多个应用程序共享(indexedDB-)缓存资源。
例如:
//hosted on https://site1.com
<!doctype html>
<html lang="en">
<head></head>
<body>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceWorker1.js', {scope: ' '}).then(function() {})
}
</script>
//serviceWorker1.js
importScripts("https://serviceWorker.com/sw.js");
//hosted on https://site2.com
<!doctype html>
<html lang="en">
<head></head>
<body>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceWorker2.js', {scope: ' '}).then(function() {})
}
</script>
//serviceWorker2.js
importScripts("https://serviceWorker.com/sw.js");
//https://serviceWorker.com/sw.js
self.addEventListener('fetch', function(event) {
// I wanted indexedDB here to be scoped under https://serviceWorker.com,
// not https://site1.com or https://site2.com
});
我已经想出了以下内容:
我想知道以下内容:
是否可以在脚本的外来源下创建一个indexedDB,通过importScripts()导入?
如果是这样,怎么样?如果没有,为什么?
提前致谢。
答案 0 :(得分:1)
没有
从中加载构成脚本的字节不会影响授予脚本访问资源的权限。例如,在从http://example.com加载的页面中,从http://example.org:1234加载的脚本与从http://example.com加载的脚本具有完全相同的权限;除了http://example.org:1234加载的脚本之外,它不能从http://example.com获取和检查任意资源。这适用于存储API以及Web平台的其他原始范围功能。
通常的解决方法是让页面托管第二个来源的iframe。帧可以使用postMessage()进行通信;托管框架限制与其信任的来源的通信。通常,此通信将包装在某种代理中,以便托管页面只能看到异步存储API。