2

I want my button to go back to the last URL with /furniture/ in it.

In the w3schools documentation is says:

The parameter can either be a number which goes to the URL within the specific position (-1 goes back one page, 1 goes forward one page), or a string. The string must be a partial or full URL, and the function will go to the first URL that matches the string.

https://www.w3schools.com/jsref/met_his_go.asp

Because it's Squarespace I have to use an event listener to add custom functionality to a Squarespace button.

<script>
  window.onload=function(){
    document.getElementsByClassName("sqs-block-button-element").addEventListener("click", goBack);

    function goBack() {
    window.history.go("https://uk5-shop.com/furniture/");
    }
  }
</script>

As far as I understand it this should send me back to any product in the furniture category I visited last for example https://uk5-shop.com/furniture/chair or https://uk5-shop.com/furniture/bed . This is not the case.

I have read somewhere that this might be discontinued but then why is it in most documentation?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • maybe you can try to find it in the history with a regex ? – axel axel Jun 04 '19 at 14:59
  • You mean this? https://www.w3schools.com/jsref/jsref_obj_regexp.asp ? – Luigi Kraken Jun 04 '19 at 15:05
  • It doesn't appear as though the window.history object maintains the history stack, so you'd have to implement/maintain that yourself to be able to "search" back through entries to find partial matches. https://developer.mozilla.org/en-US/docs/Web/API/History_API – Drew Reese Jun 04 '19 at 15:05
  • 1
    @LuigiKraken yes regex has been made to find a certain substring into a big one, for a comparision its like when you use the word search in a webpage – axel axel Jun 04 '19 at 15:11
  • Note that, by default in Squarespace, `sqs-block-button-element` is a class, not an ID. – Brandon Jun 04 '19 at 15:12
  • 3
    Firstly, please note that W3Schools is most definitely not the W3C. If you're looking for a reference that's in any way reliable, use MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/history & also https://developer.mozilla.org/en-US/docs/Web/API/History_API. Secondly you cannot pass a string to `history.go()` - it accepts an integer which is the index of how many items forward/backward you want to traverse in the history. It does not work how you seem to be expecting. – Rory McCrossan Jun 04 '19 at 15:17
  • @Brandon good point that doesent fix it though. – Luigi Kraken Jun 04 '19 at 15:21
  • @RoryMcCrossan Thanks for the advice still new to web development :) Ill make sure to only use these resources in the future. – Luigi Kraken Jun 04 '19 at 15:23
  • Possible duplicate of [history.go('url') issue](https://stackoverflow.com/questions/6277283/history-gourl-issue) – Heretic Monkey Jun 05 '19 at 14:59

1 Answers1

2

1. Description :

As answered in Another question: (https://stackoverflow.com/a/6277304/4718434)

Supplying a URL as a parameter is a non-standard feature and will not work in all browsers (as well as google chrome). Most browsers accept only a relative number, e.g. 1 or -1.

BUT: Why you want to use history.go(partialUrl) ?

  • Case 1: you just want to go to a page in user visit history, and you don't care about browser "go back" and "go forward" buttons.
  • Case 2: you want to simulate "go back" button.

In case 1, you can use cookies to save history.

But in case 2, you can save history in cookies and simulate back button, but if user play with back and forth buttons, we can't do anything and script will not be accurate anymore.


2. Script:

NOTE: this script save temp cookies, so when user close browser history will clear. if you want permament history, change setCookie function (use this link).

in start of every page (even the page that you want to use history.go), add this script to save current url in a temp cookie:

appendToCookie('history', window.location.href);

for going back to a url that maches partial url, add this (also make sure you added previus script in start of this page as well (just once)):


//last parameter description (searchFullWebsiteHistoryAndGoForwardNotBackward) :
//1. for usage case 1 described above, set it to true
//2. for usage case 2 described above, set it to false

var wentSuccessfull = goBackToHistoryWithPartialUrl('history','/some/partial/Url',false);
if(!wentSuccessfull) console.log('the pattern doesnt exists in history!');

function goBackToHistoryWithPartialUrl(historyCookieName, partialUrl, searchFullWebsiteHistoryAndGoForwardNotBackward){
  var history = getArrayFromCookie(historyCookieName);
  var historyIndex = null;
  for(var i = history.length - 2 ; i >= 0; i--){
    if( history[i].indexOf(partialUrl) >-1){
      historyIndex = i;
      break;
    }
  }
  if(historyIndex !== null){
    if (searchFullWebsiteHistoryAndGoForwardNotBackward){
      window.location.href = history[historyIndex];
    }
    else{
      var is = [];
      for(var i = history.length - 1 ; i >= historyIndex; i--){
        is.push(i);
      }
      removeMultiFromCookie(historyCookieName,is);
      //waitForCookieToSet();
      window.history.go(historyIndex - (history.length - 1));
    }
    return true;
  }else{
    return false;
  }
}

helper functions:

function getSeparator() {
  return '_#_SEP_#_';
}

function getArrayFromCookie(cookieName){
  var c = getCookie(cookieName);
  var a = c.split(getSeparator());
  return !c ? [] : a;
}

function appendToCookie(cookieName, value){
  var a = getArrayFromCookie(cookieName);
  a.push(value);
  setCookie(cookieName, a.join(getSeparator()));
}
function removeFromCookie(cookieName, index){
  var arr = getArrayFromCookie(cookieName);
  arr.splice(index,1);
  setCookie(cookieName, arr.join(getSeparator()));
}
function waitForCookieToSet(){
    //https://stackoverflow.com/questions/17583250/javascript-delete-cookie-before-reload-or-redirect
    var fakeAjax = new XMLHttpRequest();
    var anything = fakeAjax.responseText;
    fakeAjax.open("GET","ajax_info.txt",false);  // file doesn't actually exist
    fakeAjax.send();
}
function removeMultiFromCookie(cookieName, indices){
  var arr = getArrayFromCookie(cookieName);
  for(var i = indices.length - 1 ; i>=0 ; i-- )arr.splice(indices[i],1);
  setCookie(cookieName, arr.join(getSeparator()));
}
function setCookie(cname, cvalue) {
  document.cookie = cname + "=" + cvalue + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
yaya
  • 7,675
  • 1
  • 39
  • 38
  • Ok this should not be a problem though. The current page does not contain /furniture/ rather its uk5-shop.com/stoff . Where can I find the proper format or a working example your the first answer to actually claim this works? – Luigi Kraken Jun 05 '19 at 07:53
  • @LuigiKraken your `getElementByClassName` is wrong as well. see updated answer. and please put "alert('something')" in your goBack function, to make sure the problem is with "window.history". and plus, if there is a problem with code, you should press f12 and see the console tab in runtime, it says whats the error and which line is wrong. you can debug with seeing this (browser developers window (f12), the console tab) – yaya Jun 05 '19 at 09:21
  • The function is indeed running but it always sends me back a single page instead of going back to the last page in the furniture category. I have no error messages its all running with out a hick up its just not the desired result. I have only implemented it in a single page so far. Here is the link if your intresetd its the button at the bottom that reads "Zurück zum Produkt" [link](https://uk5-shop.com/stoff2) – Luigi Kraken Jun 05 '19 at 10:42
  • @LuigiKraken also you probably need case 1, so change goBackToHistoryWithPartialUrl third parameter to true. – yaya Jun 05 '19 at 16:58
  • also if you want permanent(90 day for example, you can change 90 in the code) history, change setcookie function to: function setCookie(cname, cvalue) { var d = new Date(); d.setTime(d.getTime() + (90*24*60*60*1000)); var expires = "expires=" + d.toGMTString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } – yaya Jun 05 '19 at 17:08