Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the query string on the called javascript file

Is it possible to get the query parameters with javascript on the called javascript file like this:

// in html
<script src="/file.js?query=string"></script>

// in file.js
console.log(this.location.query)

Is this possible somehow, or I have to use the server?

like image 626
Adam Halasz Avatar asked Mar 05 '13 12:03

Adam Halasz


People also ask

What is JavaScript query string?

Answer. A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.

How do I get query string in react?

Get a single Query String value location.search object: import React from 'react'; import { useSearchParams } from 'react-router-dom'; const Users = () => { const [searchParams] = useSearchParams(); console. log(searchParams); // ▶ URLSearchParams {} return <div>Users</div>; };

How do I check if a query string parameter exists?

Check if a query string parameter exists The URLSearchParams.has() method returns true if a parameter with a specified name exists.


2 Answers

You may append id attribute to script tag like this:

<script src="/file.js?query=string" id="query"></script>

and then call it:

console.log(document.getElementById("query").src.split("query=")[1]);

A small working sample code is below:

<html>
<head>
<script src="aaa.js?query=abcd" id="query"></script>
</head>
<body></body>
</html>

Here is the code inside of aaa.js:

window.onload=function(){
    alert(document.getElementById("query").src.split("query=")[1]);
}
like image 140
haitaka Avatar answered Oct 01 '22 07:10

haitaka


I could get src with below code. So I think that you can parse queryString.

document.currentScript.src
like image 45
Igari Takeharu Avatar answered Oct 01 '22 06:10

Igari Takeharu