Check if user is from external or internal page


I have made a dynamic link on my clients website.

The logic is simple, if the user reaches the page from the frontpage or an external website, then the dynamic link will point the user back to an overview page by a certain link.

However, if the user reaches the page from the overview page ( where the link opens in a new tab / target="_blank"), then the tab closes when the user click on the dynamic link.

This is my code:

* make single page "back to overview" link dynamic */
function mik_dynamic_single_car_link() {
    if( trim($_SERVER['HTTP_REFERER']) === '' || $_SERVER['HTTP_REFERER'] === home_url( '/' ))  {
        return home_url( '/' ) . "cars/example/";
        return "'','_self').close();";

However, this doesn't work on my clients server. Right now the dynamic link always redirects the user back to the overview page. In other words, the javascript is never trickered.

I have read something about that it is possible to check the session to accomplish this, however, I have not found the solution to implement this method.