外来源indexedDB缓存?

时间:2018-02-08 18:11:17

标签: javascript browser-cache indexeddb service-worker same-origin-policy

简短版

是否可以在脚本的外来源下创建一个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
});

我已经想出了以下内容:

  • 需要通过https(或localhost)从同一个来源调用服务工作者
  • A&#34;外国血统&#34;通过在(同源)加载的service-worker脚本文件中使用importScripts(&#34; https://serviceWorker.com/sw.js&#34;),可以将service-worker加载到当前源中。
  • 浏览器沙箱indexedDB数据库基于所谓的&#34;同源策略&#34;,它只规定来自同一来源元组(方案,网址,端口)的脚本可以在同一个缓存上运行。 (https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
  • importScripts()将一个或多个脚本导入到工作人员的范围内。

我想知道以下内容:

是否可以在脚本的外来源下创建一个indexedDB,通过importScripts()导入?

如果是这样,怎么样?如果没有,为什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

没有

从中加载构成脚本的字节不会影响授予脚本访问资源的权限。例如,在从http://example.com加载的页面中,从http://example.org:1234加载的脚本与从http://example.com加载的脚本具有完全相同的权限;除了http://example.org:1234加载的脚本之外,它不能从http://example.com获取和检查任意资源。这适用于存储API以及Web平台的其他原始范围功能。

通常的解决方法是让页面托管第二个来源的iframe。帧可以使用postMessage()进行通信;托管框架限制与其信任的来源的通信。通常,此通信将包装在某种代理中,以便托管页面只能看到异步存储API。