How to create a back button

How to create a back button

Hi,

See the code below:

import wixLocation from 'wix-location';
import wixWindow from 'wix-window';

export function button1_click(event, $w) {

	let url = wixWindow.referrer;
	wixLocation.to(url);
}

Hi,
Does it work in a dynamic page cos its not working from me

This method won’t work unless you want to go back to some external site and not to a web-page inside your own site.
If you want to have a back button that work inside your site, there are several methods:
Option 1: a back button that is in sync with your browser history, so it will do the same as clicking the browser back button:
Add an html component o your header.
Code for the html component:

<script type="text/javascript">
   window.onmessage = (event) => {if(document.referrer.indexOf('mydomain.com') >= 0) {
    history.go(-1);
}
   }
 </script>

Code for your site ("SITE panel):

export function Back_click(event) {
    $w("#html1").postMessage("");
}

Warning: it won’t work on crappy browsers such as Interet Explorer.

Option 2:
Code for your site ("SITE panel):

import {session} from 'wix-storage';
import wixSite from 'wix-site';
import wixLocation from 'wix-location';
const baseUrl = wixLocation.baseUrl;
$w.onReady(function () {
let currentPage;
if(wixLocation.url === wixLocation.baseUrl) {
    currentPage =wixSite.currentPage.url;
} else {
    currentPage = wixLocation.url.substring(baseUrl.length)
}
let recievedPageTrail = session.getItem("pageTrail");
let pageTrail = [];
let backTarget;
if(recievedPageTrail === null) {
    $w("#btnBack").disable();
    } else {
        $w("#btnBack").enable();
        pageTrail = recievedPageTrail.split(",");
    }
if(currentPage !== pageTrail[pageTrail.length - 1]) {
    pageTrail.push(currentPage);
} 
backTarget =  pageTrail[pageTrail.length -2]
if (pageTrail.length === 1) {
    $w("#btnBack").disable();
}    
session.setItem("pageTrail", pageTrail);

$w("#btnBack").onClick( () => {
    pageTrail.pop();
    session.setItem("pageTrail", pageTrail);
    wixLocation.to(backTarget);
})
});

Note: this code allows you to hit BACK again ad again back to very first page.
If you want to go only 1 page back and that’s all, you can make it much shorter.
Warning: it won’t be in-sync with your browser back button.

You can create a combination of the code options for the different browsers.