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.
Related
I have this script code:
<script src="http://example.com/embed.js?q=123¶meter1=450¶meter2=300"></script>
How can i get the values of q(123)and parameter1(450) and parameter2(300) and use them into embed.js file? I want to make conditions into my embed.js by using these values. How can i achieve that?
Give the script element and ID attribute like this:
<script id="embed-script" src="http://example.com/embed.js?q=123¶meter1=450¶meter2=300"></script>
Javascript:
var url = document.getElementById('embed-script');
function parseGet(val) {
var result = "",
tmp = [];
var items = url.src.split("?")[1].split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val)
result = decodeURIComponent(tmp[1]);
}
return result;
}
Get the values like this, in embed.js:
var value1 = parseGet('q');
value1 should then be "123".
I think you can't,but you can declare all param before required your js file same as:
<script type="text/javascript">
var q = 123;
var parameter1 = 450;
var parameter2 = 300;
</script>
<script src="http://example.com/embed.js"></script>
You could place the parameters in attributes of the <script> tag.
<script src="http://example.com/embed.js" q="123" parameter1="450" parameter2="300"></script>
You can access these parameters in embed.js with
document.currentScript.getAttribute('q');
document.currentScript.getAttribute('parameter1');
document.currentScript.getAttribute('parameter2');
Note: document.currentScriptdoes not work on IE.
For more info check this out.
You can access script tag as the last script tag if ask for it without waiting for document load.
~function() {
var s = document.querySelectorAll("script");
s = s[s.length-1];
console.log(s.src);
}();
In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].
Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First
Here is my very simple Script
<script class="TractsScript">
$('#Add').click(function (e) {
var val = #ViewBag.ForSection;
alert(val);
});
</script>
As per example I am wanting to simply set a variable in my script or USE a Viewbag. or Model.
I haven't been able to find an answer in any of the following forums: StckTrace1,StackTraceBetterAnswer
Other Things i have tried:
var model = #Html.Raw(Json.Encode(Model))
alert(model.Sections);
alert(#ViewBag.ForSection);
What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.
var val = '#ViewBag.ForSection';
If it's an integer you need to parse it as one i.e.
var val = parseInt(#ViewBag.ForSection);
You can do this way, providing Json or Any other variable:
1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag:
ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });
2) In the View, put the script like this at the bottom of the page.
<script type="text/javascript">
var number = parseInt(#ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = #Html.Raw(#ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>
try this method
<script type="text/javascript">
function set(value) {
return value;
}
alert(set(#Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
alert(set(#Html.Raw(Json.Encode(ViewBag.UrMessage))));
</script>
Thanks
Use single quotation marks ('):
var val = '#ViewBag.ForSection';
alert(val);
When you're doing this
var model = #Html.Raw(Json.Encode(Model));
You're probably getting a JSON string, and not a JavaScript object.
You need to parse it in to an object:
var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);
In first page im getting value in textbox i need to pass it to another page which is divided into 2 frames.
I need to display that value in first frame's html page.
Please provide me a simple example.
I tried with
window.document.getElementById("inputbox1").value
but im unable to get the value.
Please provide me a simple example.
I would go with localStorage, as #MicrosoftGoogle propose, but is not well supported yet, you can use pure javascript to achieve this. You will have something like this on your form page:
<form action="param-received.html" method="GET">
<input type="text" id="foo" name="foo">
<input type="submit" value="Send" name="submit" id="submit">
</form>
Once you click on Send button,you will be redirect to /param-received.html?foo=hola&submit=Send.
location.search attribute contains the chain of parameters.
? concatenates the URL and the string of parameters.
& separates multiple parameters.
= assigns a value to the variable.
Here is the complete code to process data sent on param-received.html:
<script language="JavaScript">
function processForm()
{
var parameters = location.search.substring(1).split("&");
var temp = parameters[0].split("=");
l = unescape(temp[1]);
alert(l); //Dialog with the text you put on the textbox
}
processForm();
</script>
Write the value in a cookie and read the cookie from the other page.
For writing and reading cookies check here
You could use the GET part of the request or cookies
if url parameters are an option you could use this
function getParameter(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
getParameter("page");
ref
http://bloggerplugnplay.blogspot.in/2012/08/how-to-get-url-parameter-in-javascript.html
another might be cookies
was beaten to the cookie part :p
edit indeed not a good cookie reference
this one is better http://www.w3schools.com/js/js_cookies.asp
function getValue(varname)
{
var url = window.location.href;
var qparts = url.split("?");
if (qparts.length == 1)
{
return "";
}
else{
var query = qparts[1];
var vars = query.split("&");
var value = "";
for (i=0;i<vars.length;i++)
{
var parts = vars[i].split("=");
if (parts[0] == varname)
{
value = parts[1];
break;
}
}
value = unescape(value);
// Convert "+"s to " "s
value.replace(/\+/g," ");
return value;
}
}
var VariableGot = getValue(YourPassingVariableName);
Just copy the function into your html file and pass your variable name to the function which is send through GET Method.Now You will get the value of the variable from url.
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;
}