Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 497
ol30cean0 Avatar asked Oct 17 '13 02:10

ol30cean0


People also ask

What is history Go (- 1?

history.go(0) reloads the page. history.go(-1) is the same as history. back() . history.go(1) is the same as history. forward() .

How do you check if the user can go back in browser history or not?

To check if the user can go back in browser history or not with JavaScript, we can call history. back or history.go . history.go(-1); to go back to the previous page.

How do I check stack history?

history object allows you to access the history stack of the browser. To navigate to a URL in the history, you use the back() , forward() , and go() methods. The history. length returns the number of URLs in the history stack.

How do you go one step back in JavaScript?

back() is the same as history.go(-1) . history. back() is the same as clicking "Back" your browser.


1 Answers

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>
like image 155
hexacyanide Avatar answered Sep 22 '22 14:09

hexacyanide