开发者

getting last page URL from history object - cross browser?

开发者 https://www.devze.com 2023-02-06 20:45 出处:网络
Is it possible to get last page URL from the history object? I\'ve come accross history.previous but that\'s either u开发者_如何转开发ndefined or protected from what I\'ve seen.Not from the history ob

Is it possible to get last page URL from the history object? I've come accross history.previous but that's either u开发者_如何转开发ndefined or protected from what I've seen.


Not from the history object, but from document.referrer. If you want to get the last actual page visited, there is no cross-browser way without making a separate case based on support for each property.


You cant get to history in any browser. That would be a serious security violation since that would mean that anyone can snoop around the history of their users.

You might be able to write a Browser Helper Object for IE and other browsers that give you access to that. (Similar to the google toolbar et al). But that will require the users to allow that application to run on their machine.

There are some nasty ways you can get to some history using some "not-so-nice" ways but I would not recommend them. Look up this link.


Of course, as people have said, its not possible. However what I've done in order to get around this limitation is just to store every page loaded into localStorage so you can create your own history ...

function writeMyBrowserHistory(historyLength=3) {
  // Store last historyLength page paths for use in other pages
  var pagesArr = localStorage.myPageHistory
  if (pagesArr===null) { 
        pagesArr = [];
  } else {
        pagesArr = JSON.parse(localStorage.myPageHistory);
        pagesArr.push(window.location.pathname)  // can use whichever part, but full url needs encoding
  }
  if (pagesArr.length>historyLength) {
        // truncate the array
        pagesArr = pagesArr.slice(pagesArr.length-historyLength,pagesArr.length)
  }
  // store it back 
  localStorage.myPageHistory = JSON.stringify(pagesArr);
  // optional debug
  console.log(`my page history = ${pagesArr}`)
}

function getLastMyBrowserHistoryUrl() {
  var pagesArr = localStorage.myPageHistory
  var url = ""
  if (pagesArr!==null) { 
    pagesArr = JSON.parse(localStorage.myPageHistory);
    // pop off the most recent url
    url = pagesArr.pop()
  }
  return url
}

So then on a js in every page call

writeMyBrowserHistory()

When you wanna figure out the last page call

var lastPageUrl = getLastMyBrowserHistoryUrl()

Note: localStorage stores strings only hence the JSON.

Let me know if I have any bugs in the code as its been beautified from the original.

0

精彩评论

暂无评论...
验证码 换一张
取 消