Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

javascript - How to add browser/session history to this website?

I have built a simple website which pulls a random meme using an API.

I am trying to make it so that when the user clicks the "back" button on their browser, they will see the last meme and so on.

At the moment, on each page refresh, a new meme is pulled. How can I add history to this website?

Here is the code for the JS:

fetch("https://meme-api.herokuapp.com/gimme")
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
    console.log(data.title);

    if (data.nsfw) {
      location.reload();
    } else {
      let UIdiv = document.getElementById("root");
      let UIh2 = document.querySelector("h2");

      UIh2.innerText = data.title;

      let UIimg = document.createElement("img");

      UIimg.style.maxWidth = "500px";
      UIimg.style.display = "block";
      UIimg.style.marginLeft = "auto";
      UIimg.style.marginRight = "auto";

      UIimg.src = data.url;

      UIdiv.appendChild(UIimg);
    }
  })

  .catch((error) => {
    let UIheader = document.querySelector("h1");
    UIheader.innerText("An error occurred, please refresh the page!");
  });

question from:https://stackoverflow.com/questions/65651967/how-to-add-browser-session-history-to-this-website

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try to add in your HTML page the followin button

<input type=button value='Back' onclick='window.history.go(-1); return false;'>

or make it as a link like:

<a href="www.mypage.com" onclick="window.history.go(-1); return false;">Back </a>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...