How to take Settings from a URL and put in a Button?

Asked

Viewed 49 times

1

how to make one page redirect to another using URL parameters

for example: www.dominioaqui.com.br/index.html? link=https://www.google.com

in this example I have a page with a button that redirects to the parameter inserted in "? link=" that would be Google.

this way I can use the same page with several parameters, without having to create a different page for each link

a code I found but tried to use and it didn’t work

Carry on
<script>
    var path = location.pathname+location.search;
    var meusiteid  = 'https://www.meusite.com.br' + path;
    document.getElementById('linknaurl').addEventListener('click', function (e) {window.location.replace(meusiteid);});
</script>

2 answers

0


There are many ways to read the url parameters that are in location.search.

Here are several solutions: https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript

I took an example and adapted your question:

function get(query, chave) {
    var half = query.split('&' + chave + '=')[1];
    if (!half) half = query.split('?' + chave + '=')[1];
    return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}


// Usei a variável com um conteúdo para demonstrar sem precisar "vir" de outro link, mas a variável url deve pegar location.search
// var url = window.location.search;
var url = "http://www.dominioaqui.com.br/index.html?link=https://www.google.com";

var meusiteid = get(url, "link");

if (meusiteid != null) {
    document.getElementById('linknaurl').addEventListener('click', function (e) {   window.location.replace(meusiteid);});
}
<button id="linknaurl">Clique aqui para redirecionar</button>

  • Thank you very much! it worked.

0

So you can work with querystring of a URL, you can use the interface Urlsearchparams javascript.

Suppose you have the following URL:

https://domain.com/?product=pant&color=blue&size=m

For you to catch the querystring, do the following:

const queryString = window.location.search;
console.log(queryString)
// ?product=pant&color=blue&size=m

Once having the value of querystring in a constant, instate an object Urlsearchparams, passing this constant as a parameter:

const urlParams = new URLSearchParams(queryString);

To pick a specific parameter, use the method get():

const product = urlParams.get('product')
console.log(queryString);
// pant

To check if a particular parameter exists, use the method has(), passing the name of this parameter as a function parameter:

console.log(urlParams.has('color'));
// true
console.log(urlParams.has('quantity'));
// false

If you want to know more details about this inteface, click on this link.

Browser other questions tagged

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