简体   繁体   中英

JS onclick="history.go(-1) only if under my domain

I have a Joomla site, and I have the following problem, I need a "Back to search page" function on my product details page, and I am using this code after some changes according to replies to my initian question:

<br/><a href="" onclick="if (document.referrer.indexOf(window.location.host) !== -1) alert('true'); { history.go(-1); return false; } else { window.location.href = 'mysite.com.br'; }"><?php echo JText::_('VOLTAR'); ?></a>

Now, if a Visitor comes from another site directly to my product page and click this, he will be redirected to homepage of my site, and this is ok, but if I in a search page of my site, click on a product page and then click on the back to search link, the visitor is also redirected to my homepage, which is not good, it should be redirected to previous page, which was his own search page.

Is there any way to modify this code in order to accomplish something like:

if visitor comes from my search page or from anywhere in my site, by clicking this he will be redirected to the previous page, and if a visitor came from outside of my site, by clicking this he will be redirected to my homepage?

You can use document.referrer and compare it to window.location.host .

if (document.referrer.split('/')[2] === window.location.host)
if (document.referrer.indexOf(window.location.host) !== -1)

So your HTML will look like this:

<a href="" onclick="if (document.referrer.indexOf(window.location.host) !== -1) { history.go(-1); return false; } else { window.location.href = 'website.com'; }"><?php echo JText::_('VOLTAR'); ?></a>

Adding branching logic into an inline click handler gets messy. If you can move this to a function and reference it it will be far more readable.

if(document.referrer.indexOf('mysite.com') >= 0) {
    history.go(-1);
}
else {
    window.location.href = 'myHomePageUrl'; // this might just be '/' of your site
}

Edit: If you are not concerned about adding names to the pages global scope you can create a function in a script tag immediately before the link you are creating:

<script>
    function backClick() {
        // above conditional goes here.
        return false;
    }
</script>
<br/><a href="" onclick="backClick()"><?php echo JText::_('VOLTAR'); ?></a>

I have tried some of the codes above and I needed to make some changes to make it work for me.

  1. remove href=""
  2. "window.location.href" must have http://

 function backClick() { if (document.referrer.indexOf(window.location.host) !== -1) { history.go(-1); return false; } else { window.location.href = 'https://stackoverflow.com'; } }
 <a onclick="backClick()">go back</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM