How to store and retrieve the previous URL within the Cookie

Posted on

Question :

The whole script is in the bookmarks / bookmarks bar, called: Bookmarklet

I’ve already done script . See:

Before c / referrer

javascript: var URL = document.referrer; location.href = URL;

Now with cookie

javascript: var URL = window.location; link = document.cookie; link = URL; location.href = link;

Unfortunately, I’m not able to mimic the method referrer with a cookie . That would be my interest.

Does anyone have an idea how to reference a previous URL without using the method document.referrer ?


Answer :

You can use Cookie to do this. Keep in mind that a cookie is not secure.

To use a Cookie you should use chave=valor; format so that you can put together several cookies and you always know which one is which.

So in this case, to write:

document.cookie = 'ultimoUrl=' + window.location.href;

To read, you need to get the string value of document.cookie and you can do this:

function lerCookie(nome) {
    var regex = new RegExp('(?:(?:^|.*;s*)' + nome + 's*=s*([^;]*).*$)|^.*$');
    return document.cookie.replace(regex, "$1");

document.cookie = 'MeuCookie=SOpt;';
console.log(lerCookie('MeuCookie')); // 'SOpt'

jsFiddle : link


If you just want to redirect via “Favorites” use this:

// Pega o link atual
var link = window.location.href; 

// Redireciona para o site contendo o link""+link);

Do the same as you asked to do, it will have the same result without any page or HTML being injected or created. ;)

Supposedly to support Favicon by creating such elements:

$('head').html("<link rel='image_src' href=''><script>''+window.location.href, '_self');</script>");

In this case it is necessary to load JQuery, this will result in:

  • None of the three options presented Favion in the browser tested, but the last one mentioned here behaves similarly, I do not know to what extent it is sufficient.

Leave a Reply

Your email address will not be published. Required fields are marked *