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?
Answer. A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.
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>; };
Check if a query string parameter exists The URLSearchParams.has() method returns true if a parameter with a specified name exists.
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]);
}
I could get src with below code. So I think that you can parse queryString.
document.currentScript.src
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With