页面之间不共享本地存储

时间:2019-05-03 14:04:52

标签: javascript html5 epub epub3

我有一本3页的epub3书。我正在Mac OSX上的Apple图书(内置的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>
<title>My Book</title>
<meta charset="utf-8"/>

<script>
/*<![CDATA[*/

window.addEventListener('focus', function(event) {

  var currentPage = localStorage.getItem('currentPage')
  if (currentPage == null){
     currentPage = "";
  }

  currentPage = currentPage + " 1";

  localStorage.setItem('currentPage', currentPage);
});

setInterval("myFunction()", 1000);

function myFunction() {
    var t = document.getElementById("currentPage");

    var currentPage = localStorage.getItem('currentPage');
    if (currentPage == null){
       currentPage = "";
    }

    t.innerHTML = currentPage;
}


/*]]>*/
</script> 

</head>

<body> 
<h1> Page 1</h1>

<div id = "currentPage"></div> 

</body> 
</html>

随后的页面使用相同的模式。

因此,当我打开以前打开过的书时,每页显示相同的值,例如:

Page 1: 1 2 1 2 3 
Page 2: 1 2 1 2 3 
Page 3: 1 2 1 2 3 

但是,当我在页面之间切换焦点时,页面更新如下:

Page 1: 1 2 1 2 3 1 1 1 1 1 1 1 1
Page 2: 1 2 1 2 3 2 2 2 2 2 2
Page 3: 1 2 1 2 3 3 3 3 3

因此,每个页面看起来都有自己的独立本地存储变量。我希望变量可以在页面之间共享。

当我关闭书本时,页面上显示的具有焦点的值将存储到本地存储中,并且在再次打开书本时将使用该值。

我是OSX 10.14。我已经在Apple Books(1.16)中对此进行了测试。我应该如何正确共享页面之间的状态?

1 个答案:

答案 0 :(得分:7)

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

饼干

在该用例中,它的性能不如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

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

<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"
    },

    // ...
]

窗口引用

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