How to change URL objects via Javascript?

Asked

Viewed 1,590 times

3

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

3 answers

4


I’m not sure that’s what you’re looking for, but this fragment that starts with # is called hash and can be obtained and amended accordingly:

// 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);
}
  • But as I Linko this function?

  • 1

    In your link’s onclick, simply change the hash using the second line of my example.

2

You can’t just put this code into the attribute itself href of the link?

<a href="#gsc.tab=1">Pesquisar por imagens</a>

2

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

window.location.hash

From there 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;
}

Here’s an example that works even though jsFiddle doesn’t show the HASH in the url: http://jsfiddle.net/hym346sw/

The result of the example is:

"[
    {
        "chave": "teste",
        "valor": "10"
    },
    {
        "chave": "outro.Teste",
        "valor": "20"
    }
]"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.