How to change URL objects via JavaScript?

3

I have a search engine on my site using Google Custom Search, and to set search by images, it is added in the URL: #gsc.tab=1 . How do I create a system in JS that can be executed via link that adds this in the URL?

    
asked by anonymous 01.11.2014 / 00:01

3 answers

5

I'm not sure if this is what you're looking for, but this snippet that begins with # is called hash and can be obtained and changed like this:

// pega o valor atual
var hashAtual = window.location.hash;

// troca o valor
window.location.hash = 'foo';

// monitora trocas de valor
window.onhashchange = function() {
    console.log('hash trocado para ' + window.location.hash);
}
    
01.11.2014 / 00:12
2

To read the hash that is in the URL you can use:

window.location.hash

From here you have to remove the values you want with a function like this below:

function getHASH() {
    var hash = window.location.hash.slice(1);
    var pares = hash.split('&');
    var chaves = pares.map(function (par) {
        var chave_valor = par.split('=');
        return {
            chave: chave_valor[0],
            valor: chave_valor[1]
        };
    });
    return chaves;
}

This is an example that works even though jsFiddle does not show HASH in the url: link

The result of the example is:

"[
    {
        "chave": "teste",
        "valor": "10"
    },
    {
        "chave": "outro.Teste",
        "valor": "20"
    }
]"
    
01.11.2014 / 00:45
2

Can not you just put this code in the href attribute of the link?

<a href="#gsc.tab=1">Pesquisar por imagens</a>
    
03.11.2014 / 16:34