How do I get query string value from script path? - javascript

I am adding my Javsacript file in pages with different query strings in the script path like this:
Page1:
<script type="text/javascript" src="file.js?abc=123"></script>
Page2:
<script type="text/javascript" src="file.js?abc=456"></script>
Page3:
<script type="text/javascript" src="file.js?abc=789"></script>
In my Javascript file, how can I get the value of the "abc" param? I tried using window.location for this, but that does not work.
In case it helps, below is a function I use to find the value of a query string param:
function getQuerystring(key, defaultValue) {
if (defaultValue == null) defaultValue = "";
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null)
return defaultValue;
else
return qs[1];
}

This is possible. See Passing JavaScript arguments via the src attribute. The punchline is that since scripts in HTML (not XHTML) are executed as loaded, this will allow a script to find itself as it is always the last script in the page when it’s triggered–
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\?]+\??/,'');
Then you just apply the query string parsing.

First, the technical answer: if you assign your script tag an ID, you can then grab its src and then parse out the query string.
<script id="whatever" type="text/javascript" src="file.js?abc=123"></script>
var path = document.getElementById('whatever').src;
// ...
With that answered, I'd like to voice my concern — this reeks of poor design decisions. Why are you including your script this way (with a querystring)? If you're trying to optimize your site (by having one large script that can be cached for subsequent pages), this approch is actually counter-productive because browsers will make a fresh request for the script file on each page due to the differing query string. The correct approach is to have one large shared file and then a small page-specific file on each page.

Since there is no more significant use of Internet Explorer. You can use document.currentScript and new URL, which return a string with the tag <script> in question.
const search = new URL(document.currentScript.src).search.substring(1)
const stringPreparation = decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')
const qs = JSON.parse('{"' + stringPreparation + '"}')
You can reduce this code to one line, but it is not recommended, let minifier scripts do that.

You can use the URL api and document.currentScript to retreive this`
const url = new URL(document.currentScript.getAttribute('src'));
const scriptParams = Object.fromEntries(url.searchParams)
console.log(scriptParams);

I have a quick and easy solution for extracting the query string from a js file using jQuery to grab the script tag source attribute and simply using two separate functions for parsing the JS file path and query string. Obviously, jQuery is required.
$(document).ready(function() {
var p = parseURL($('script[src*="thisfile.js"]').attr('src'));
console.log(p);
});
// Parse a URL into its parts
function parseURL(url)
{
var p = document.createElement('a');
p.href = url;
var obj = {
'protocol' : p.protocol,
'hostname' : p.hostname,
'port' : p.port,
'pathname' : p.pathname,
'search' : p.search,
'query' : p.search.substring(1),
'args' : parseStr(p.search.substring(1)),
'hash' : p.hash,
'host' : p.host
};
return obj;
}
// Parse a query string
function parseStr(string)
{
var args = string.split('&');
var argsParsed = {};
for (i = 0; i < args.length; i++)
{
var arg = decodeURIComponent(args[i]);
if (arg.indexOf('=') == -1)
{
argsParsed[arg.trim()] = true;
}
else
{
var kvp = arg.split('=');
argsParsed[kvp[0].trim()] = kvp[1].trim();
}
}
return argsParsed;
}

Related

C# get a value from script using WebRequest

I need to get a value from script in Webrequest's response. The code is like :
<script type="text/javascript">
var CUS = CUS || {};
CUS.namespace('CUS.model');
CUS.model.page = {"Key":"needed Value"};
<script>
I can deserialize that json if i get, Is there any nice using for this getting process?
Edit : Let me try to complain; I get a response from a HttpWebRequest and its a html document like below
string result;
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(result);
"result" variable have :
<script type="text/javascript">
var CUS = CUS || {};
CUS.namespace('CUS.model');
CUS.model.page = {"Key":"needed Value"}//It seems like json!;
<script>
I need to get after the "CUS.model.page =" thing.
You could use a regular expression to extract the key.
string result = #"
<script type=""text/javascript"">
var CUS = CUS || {};
CUS.namespace('CUS.model');
CUS.model.page = {""Key"":""needed Value""}//It seems like json!;
<script>";
Match match = Regex.Match(input, #"(CUS\.model\.page\s*=\s*)({""Key"":"")(.*)(""})");
string key = match.Success ? match.Groups[3].Value : null;
You can adapt the regular expression to make it more robust, in case the content in the script tag changes in the future.

Getting query string parameters from clean/SEO friendly URLs with JavaScript

I've recently switched my site to use clean/SEO-friendly URLs which has now caused me some issues with a JavaScript function I had for grabbing the query string parameters.
Previously I had been using this function:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
Which worked fine on things like this as you could just call getQueryVariable("image") and return "awesome.jpg".
I've been playing with the indexOf(); function to try and grab the relevant parameters from the current URL, eg:
var url = window.location.pathname;
var isPage = url.indexOf("page") + 1;
In an attempt to get the array index number of the "page" parameter, and then plus 1 it to move along to the value of that (?page=name > /page/name/)
JavaScript isn't my main language, so I'm not used to working with arrays etc and my attempt to turn this into a new function has been giving me headaches.
Any pointers?
How about something like this? It splits the path and keeps shifting off the first element of the array as it determines key/value pairs.
function getPathVariable(variable) {
var path = location.pathname;
// just for the demo, lets pretend the path is this...
path = '/images/awesome.jpg/page/about';
// ^-- take this line out for your own version.
var parts = path.substr(1).split('/'), value;
while(parts.length) {
if (parts.shift() === variable) value = parts.shift();
else parts.shift();
}
return value;
}
console.log(getPathVariable('page'));
This can be done formally using a library such as router.js, but I would go for simple string manipulation:
const parts = '/users/bob'.split('/')
const name = parts[parts.length - 1] // 'bob'

Display page name in javascript?

How would I add location.href.split('/').pop() to a html document to display the page name? (not the whole URL) I would like to display the page name ONLY.
example:
if the page was "www.example.com/whaterver/mypage.html"
it would display "mypage".
What would be the full script? I am new to javascript and I found this online but I don't know the whole code. could anyone help me out?
I would stick it in a function in case you need to reuse it elsewhere in your code. Just split the page name at the end and take the first element:
function getPageName(url) {
return url.split('/').pop().split('.')[0];
}
You can pass in the actual URL:
var pageName = getPageName('www.example.com/whaterver/mypage.html'); // mypage
Or, using location.href:
var pageName = getPageName(location.href); // mypage
I might also be inclined to return something if there is no match for *.html, so here's a revised function that returns null if there isn't a match:
function getPageName(url) {
var pageName = url.split('/').pop().split('.')[0];
return pageName.length > 0 ? pageName : null;
}
DEMO
Note: If you do .split('.') like other solutions instruct, you will miss the base names from many URLs.
You can find the last forward slash and search ahead for the first ., ?, & or # to catch variations of URLs. This is the equivalent of PHP's basename
function getBaseName(url) {
if(!url || (url && url.length === 0)) {
return "";
}
var index = url.lastIndexOf("/") + 1;
var filenameWithExtension = url.substr(index);
var basename = filenameWithExtension.split(/[.?&#]+/)[0];
// Handle '/mypage/' type paths
if(basename.length === 0) {
url = url.substr(0,index-1);
basename = getBaseName(url);
}
return basename ? basename : "";
}
and use it like so
var url = "http://www.example.com/whaterver/mypage.html";
var file = getBaseName(url);
of
var file = getBaseName(location.pathname); // The current script page
Results:
http://www.example.com/whaterver/mypage/ => "mypage"
http://www.example.com/whaterver/mypage.html => "mypage"
http://www.example.com/whaterver/mypage => "mypage"
http://www.example.com/whaterver/mypage/ => "mypage"
http://www.example.com/whaterver/mypage#works => "mypage"
http://www.example.com/whaterver/mypage?ver=1 => "mypage"
JSBin Demo

Extracting parameters from JavaScript include tag using a Regex

I am currently trying to parse parameters from a path to a JavaScript file (inside a script tag). At the moment I know which parameters I expect to be there but instead of looking for the expected params I would rather like to just extract all params given.
Example of the script tag which includes a JavaScript file:
<script type="text/javascript" src="https://url/widget.js?param1=A&param2=bb></script>
At the moment I'm just doing this (seperately for each parameter):
jQuery('script').each(function() {
var script = this;
if (!script.src) {
return;
}
var matchKey = script.match(/https\:\/\/url\/widget\.js\?param1=([A-Z]+)/);
if (matchKey) {
oSettings.param1 = matchKey[1];
}
}
So what I need is a regex that extracts both the name of the parameter and the value from the included sript.
Thanks for the assistance!
This tested function works:
function parse_query_vars(text)
{ // Extract name=value pairs from URL query string.
// Empty object to store name, value pairs.
var qvars = {},
// Capture non-empty query string in $1.
re_q = /\?([^#]+)/, // From '?' up to '#' or EOS.
// Capture variable name in $1 and value in $2.
re_nv = /([^=]+)=([^&]*)(?:&(amp;)?|$)/gi,
// Match array for query string and va=val pairs.
m = text.match(re_q),
// Query string plucked from URL
q = '';
// If there is a query string, copy to q var.
if (m) q = m[1];
while (m = re_nv.exec(q)) {
qvars[m[1]] = m[2];
}
return qvars; // Return results in object
}
It first extracts any query string from the URL, then iteratively parses out name=value pairs and returns the results in an object. It handles name value pairs separated by either & or & and works if the URL has a #fragment following the query.
Use something like this, or this, or this.
They're not all regex solutions, but then you don't necessarily need a regex. That was a detail that could probably have been left out of the question.
Hope that helps.
(This isn't actually tested)
var scripts = document.getElementsByTagName("script"), i = scripts.length;
var reMatch = /https\:\/\/url\/widget\.js/, path;
// find the correct script
do {
path = scripts[i--].src;
}
while (!reMatch.test(path));
var map = {}, pairs = path.substring(path.indexOf("?") + 1).split("&"), atoms;
i = pairs.length;
// extract the name-value pairs
while (i--) {
atoms = pairs[i].split("=");
map[decodeURIComponent(atoms[0])] = decodeURIComponent(atoms[1]);
}

Can a javascript attribute value be determined by a manual url parameter?

I am trying to display data from an external .jsp file, which is set up something like this:
<tag>
<innertag1 id="1">
<innertag1 id="2">
</tag>
<tag>
<innertag2 id="3">
<innertag2 id="4">
</tag>
To display only information from only one particular "innertag" tag, I'm currently using:
NodeList labs = XMLInfo.getElementsByTagName("innertag1");
I'd like to be able to isolate any particular tag with ease. Theoretically, I could create many individual pages and simply change the values to "innertag2," "innertag3," etc., but this is obviously a bit impractical.
Is there a way to determine the value via a URL parameter? For instance, if I wanted to only display data from "innertag2," is there a way that the url http://www.server.com/data.jsp?id=innertag2 would adjust the tagname properly?
Thank you, any help would be much appreciated.
You can parse document.location.href and extract parameters from there. This is from an old HTML file where I used this technique (not sure if it's compatible on all browsers, however).
var args = {};
function parseArgs()
{
var aa = document.location.href;
if (aa.indexOf("?") != -1)
{
aa = aa.split("?")[1].split("&");
for (var i=0; i<aa.length; i++)
{
var s = aa[i];
var j = s.indexOf("=");
if (j != -1)
{
var name = s.substr(0, j);
var value = s.substr(j + 1);
args[name] = value;
}
}
}
}
Not sure if this is what you're looking for, but you can access parameters from the url using location.search.
6502's answer is almost good enough, it's not url decoding parameters. The function below is a bit more polished (descriptive variable names, no global variables)
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do
var params = getUrlParams();
XMLInfo.getElementsByTagName(params['id']); // or params.id

Categories

Resources