【问题标题】:Local Storage is not shared between pages页面之间不共享本地存储
【发布时间】:2019-09-10 16:26:21
【问题描述】:

我有一本 2 页的 epub3 书以及一个目录页。我正在 Mac OSX 上的 Apple Books 中查看这本书,这是他们内置的 epub3 阅读器。两页并排出现。第一页如下:

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=500, height=600"/>
    </head>
    <body>

<p id="result"></p>

<script>
//<![CDATA[
  var current_page = "1";
  var other_page = "2";

  var t = 0;

  setInterval(function() {

    var d = new Date();
    var storage = localStorage; 

    storage.setItem("t"+ current_page, d.toLocaleString());

    document.getElementById("result").innerHTML = storage.getItem("t"+ current_page) +" "+storage.getItem("t"+ other_page);    
  }, 1000);

//]]>
</script>

    </body>
</html>

我的第二页唯一不同的是:

  var current_page = "2";
  var other_page = "1";

因此,页面 1 每秒将当前时间保存到本地存储为 t1,页面 2 对值 t2 执行相同操作。同时,两个页面都在从本地存储中读取t1t2,然后它们的值才会显示到屏幕上。但是在 ibooks 中,页面 1 仅在重新加载页面时才设法显示 t2 的当前值 - 就像我翻到目录然后再​​次返回到第 1 页和第 2 页时一样。对于第 2 页,t1 也发生了类似的事情。

所以在 21:10:00 时,第 1 页可能会显示:

08/09/19, 21:09:18 08/09/19, 21:08:58

和第 2 页:

08/09/19, 21:09:22 08/09/19, 21:08:01

我也尝试使用会话数据,但第 1 页无法读取 t2,第 2 页无法读取 t1。因此,将改为显示:

08/09/19, 21:09:18 无效

我可以想到几个应用程序,它们对于 Pages 相互通信非常有用。

例如,如果一个视频正在一个页面上播放,那么在另一个页面上的视频开始播放时停止它会很有用。这通常使用会话存储来完成。这与我自己的用例以及我开始探索这个问题的原因有关。

同样,如果要求用户在第 1 页输入故事主角的姓名,则该条目应在输入后立即出现在第 2 页上。

除了本地或会话存储之外,页面在 epub3 中还有其他方式相互通信吗?

【问题讨论】:

标签: javascript html epub epub3


【解决方案1】:

我不知道epub3,也没有要测试的MAC,但我想到了四种可能的解决方案:

Cookies

对于该用例,它的性能不如 localStorage,但如果您没有太多选择,总比没有好。

创建、读取和删除 cookie 的函数(致 https://stackoverflow.com/a/28230846/9150652):

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

你的例子的用法:

<script>
//<![CDATA[
  var current_page = "1";
  var other_page = "2";

  var t = 0;

  setInterval(function() {

    var d = new Date();

    setCookie("t"+ current_page, d.toLocaleString(), 100); // 100 days

    document.getElementById("result").innerHTML = getCookie("t"+ current_page) +" "+getCookie("t"+ other_page);    
  }, 1000);

//]]>
</script>

广播频道

BroadcastChannel 是一项非常新的功能,因此“图书”应用可能不支持它。但这里有一个概念:

<script>
//<![CDATA[
  var broadcaster = new BroadcastChannel('test');
  var current_page = "1";
  var other_page = "2";

  var t = 0;

  setInterval(function() {

    var d = new Date();

    // Send message to all other tabs with BroadcastChannel('test')
    bc.postMessage({
        senderPage: "t"+ current_page,
        date: d.toLocaleString()
    });
  }, 1000);

  broadcaster.onmessage = (result) => {
      if(result.senderPage == "t"+ other_page) { // If the message is from the other page
        // Set HTML to current date + sent Date from other page
        var d = new Date();
        document.getElementById("result").innerHTML = d.toLocaleString() +" "+result.date;    
      }
  };

//]]>
</script>

某种后端

如果上述方法都不起作用,您可能别无选择,只能使用某种后端来提供和保存数据

如果只适合您,我建议您使用 Firebase 或 MongoDB Atlas 的免费层,因为它们都在其免费层上提供了相当多的价值。

如果你用后端来做,它可以用这样的东西来做:

<script>
//<![CDATA[
  var current_page = "1";
  var other_page = "2";
  var lastLocalDate = new Date();
  const serverUrl = "http://someUrl.com/endpoint/"

  // Gets the latest date of the other page via ajax
  function getUpdate() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            // If successful, update HTML
            if (xmlhttp.status == 200) {
                document.getElementById("result").innerHTML = lastLocalDate.toLocaleString() +" "+xhr.responseText;
            }

            // Update the date of this page anyways
            sendUpdate();
        }
    };

    // GET request with parameter requestingPage, which is the other page
    xmlhttp.open("GET", serverUrl, true);
    xmlhttp.send(`requestingPage=${other_page}`);
  }

  // Sends the current date of this page to the webserver
  function sendUpdate() {
    var xmlhttp = new XMLHttpRequest();

    // No need to check if successful, just update the page again
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            getUpdate();
        }
    };

    lastLocalDate = new Date();

    // POST request with parameters page and date
    xmlhttp.open("POST", serverUrl, true);
    xmlhttp.send(`sendingPage=${current_page}&data=${lastLocalDate.toLocaleString()}`);
  }

  // Start with sending an update (so that lastLocalDate is at least sent once to the server)
  sendUpdate();
//]]>
</script>

您的后端中的一些方法需要看起来像这样(请注意,这不是任何语言的有效代码):

@GET
function getDate(requestingPageId)
    find latest entry with page.id == requestingPageId
    return page.date

@POST
function saveDate(savingPage, savingDate)
    store new page element with 
        page.id = savingPage
        page.date = savingDate

您的数据库中的集合如下所示:

[
    {
        id: 1,
        date: "date"
    },{
        id: 2,
        date: "date"
    },{
        id: 2,
        date: "date"
    },{
        id: 1,
        date: "date"
    },

    // ...
]

窗口引用

如果图书应用从第一个选项卡打开第二个选项卡,则可能值得研究一下:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    相关资源
    最近更新 更多