how can I get asp.net aspx page name from javascript? - javascript

Trying to get the aspx name from the current page from javascript?

Try this
<script language="javascript">
var url = window.location.pathname;
var myPageName = url.substring(url.lastIndexOf('/') + 1);
alert(myPageName);
</script>

As an alternative -
var page = '<%=Path.GetFileName(Request.Path)%>'
Do you want to parse the current window, or rely on asp.net?
Both work - it's up to you.

To Get The Exact Formname using jquery one can do string manipulation as shown.
$(document).ready(function () {
var path = window.location.pathname;
var page = path.substr( path.lastIndexOf("/") + 1 ).split(".",1);
var formname=page[0].toString();
alert(formname);
});

This one without the query string
$(function () {
var url = window.location.pathname;
var pageQuery = url.substring(url.lastIndexOf('/') + 1);
var page = pageQuery.split('?')[0];
)}

Related

How Render Partial view from JS in Layout

Trying to use JS to render a partial view based on the URL... This is almost working but I can't use Razor syntax in the PathRoot Var so I tried escaping it but then it doesn't render... Any Ideas would be greatly appreciated.
<head>
<script>
var SiteUrl = window.location.hostname;
var FloodlightPathRoot = '##Html.Partial("~/Views/shared/FloodlightTags/' ;
var FloodlightEnd = '");';
switch (SiteUrl) {
case "www.website.com":
var FloodlightFilePath = "first.cshtml";
break;
case "www.website2.com":
var FloodlightFilePath = "second.cshtml";
break;
}
var FloodFull = (FloodlightPathRoot + FloodlightFilePath + FloodlightEnd);
$('head').append(FloodFull);
</script>
</head>
It writes the razor syntax to the head but the page has already rendered. Can I render the razor syntax after the head is updated?
<head>
#Html.Partial("~/Views/shared/FloodlightTags/first.cshtml");
</head>
While using your code it can done this way
<head>
<script>
#{
string path = Request.RequestUri.PathAndQuery;
if (path.Contains("www.website.com"))
{
#Html.Partial("~/Views/shared/FloodlightTags/first.cshtml");
}
else if (path.Contains("www.website.com"))
{
#Html.Partial("~/Views/shared/FloodlightTags/second.cshtml");
}
}
</script>
</head>
in addition to Stephen's answer you can do it like this:
#{
var url = new Uri(new Uri(this.Context.Request.Url.GetLeftPart(UriPartial.Authority)), Url.Content("~/")).ToString();
if (url == "http://www.website.com/")
{
#Html.Partial("~/Views/shared/FloodlightTags/first.cshtml");
}
else if (url == "http://www.website2.com/")
{
#Html.Partial("~/Views/shared/FloodlightTags/second.cshtml");
}
}
var url will get the site url and then it will check weather it matches http://www.website.com/ if so it will render first.cshtml else it will check the second condition.

How to find the script path from his own js file

I want to find the script path of my own js file in itself.
So I want have as a string "C:\files\MyProject\MyScripts\MyJavaScript.js".
How is that possible?
You can try (Jquery):
var myScriptDetails = $('script');
myScriptDetails will contain details regarding the script, including its location.
Try this solution. I think this is exactly what u want :)
Put this code in each of your linked script file
var scriptEls = document.getElementsByTagName( 'script' );
var thisScriptEl = scriptEls[scriptEls.length - 1];
var scriptPath = thisScriptEl.src;
var scriptFolder = scriptPath.substr(0, scriptPath.lastIndexOf( '/' )+1 );
console.log(scriptPath +" "+ scriptFolder );// you can save these in any variable also
I tested it with this HTML code:
<!DOCTYPE html>
<html>
<head>
<title>testing...</title>
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript" src="js/test2.js"></script>
<script type="text/javascript" src="../test3.js"></script>
</head>
<body>
content area
</body>
</html>
And found this Output in console:
file:///D:/workspace/dbshell/www/test.js file:///D:/workspace/dbshell/www/ test.js:6
file:///D:/workspace/dbshell/www/js/test2.js file:///D:/workspace/dbshell/www/js/ test2.js:6
file:///D:/workspace/dbshell/test3.js file:///D:/workspace/dbshell/ test3.js:6
Special thanks to meouw..
Hope this helps..
here is how I made it:
function ScriptPath() {
var scriptPath = '';
try {
//Throw an error to generate a stack trace
throw new Error();
}
catch(e) {
//Split the stack trace into each line
var stackLines = e.stack.split('\n');
var callerIndex = 0;
//Now walk though each line until we find a path reference
for(var i in stackLines){
if(!stackLines[i].match(/http[s]?:\/\//)) continue;
//We skipped all the lines with out an http so we now have a script reference
//This one is the class constructor, the next is the getScriptPath() call
//The one after that is the user code requesting the path info (so offset by 2)
callerIndex = Number(i) + 2;
break;
}
//Now parse the string for each section we want to return
pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
}
this.fullPath = function() {
return pathParts[1];
};
this.path = function() {
return pathParts[2];
};
this.file = function() {
return pathParts[3];
};
this.fileNoExt = function() {
var parts = this.file().split('.');
parts.length = parts.length != 1 ? parts.length - 1 : 1;
return parts.join('.');
};
}
Client-side you can't access the physical path. You can get the src attribute of the script tag though.
Server-side you can get the physical path. For example (C#):
Path.GetFullPath(path)
For finding full path of URL in JavaScript use this location.href
If you can define absolute path of server as constant variable,
you can do it by casting from window.location.href. remove host prefix window.location.host from window.location.href and prepand with server's absolute path.
Try:
console.log(window.location.href);

Pass URL Parameters from one page to another

Trying to do the following:
Store params from url, i.g. mydomain.com/page.html?cid=123456
If a user clicks on a button (they have a class of .btn-cta) it will take the params ?cid=123456 and add them to the new page those buttons link to /tour.html
I'm currently doing 1/2 of that with passing the params to an iframe on the page, now I need to get the above part working:
var loc = window.location.toString(),
params = loc.split('?')[1],
iframe = document.getElementById("signupIndex"),
btn = $('.btn-cta');
iframe.src = iframe.src + '?' + params;
Here's how I'd do it using jquery:
$('.btn-cta').each(function(i, el){
let $this = $(this); // only need to create the object once
$this.attr({
href: $this.attr("href") + window.location.search
});
});
And in Vanilla ES2015
document.querySelectorAll('.btn-cta')
.forEach(el => el.attributes.href.value += window.location.search);
This takes all the elements that have class .btn-cta and appends the page query string to each of their href attributes.
So if the page url is `http://domain/page.html?cid=1234
Tour
becomes
Tour
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function() {
var loc = window.location.href;
var params = loc.split('?')[1];
$(".btn-cta").click(function(){
window.open("tour.html?"+params,'_self',false);
});
});
</script>
</head>
<body>
<button type="submit" class="btn-cta">Click Me</button>
</body>
</html>

How do I refer to the parameter passed to javascript in html?

When I call the script via
<script type="text/javascript"
src="include/javascript/test_something.js?v=1128557"></script>
how do I refer to the variable V passed in the html?
Thanks in Advance!
The most simple way would be to use a server side technology. This is in php.
<?php
$v=1128557;
?>
<script type="text/javascript">
//This will make this value available to javascript too
var val=<?php=$v?>;
</script>
<script type="text/javascript"
src="include/javascript/test_something.js?v=<?php=$v?>"></script>
...
...
...
<div id='baba<?php=$v?>'>
...
...
</div>
This will be translated to the following html
<script type="text/javascript">
//This will make this value available to javascript too
var val=1128557;
</script>
<script type="text/javascript"
src="include/javascript/test_something.js?v=1128557"></script>
...
...
...
<div id='baba1128557'>
...
...
</div>
Get it from the src attribute of the last script element in your page:
var scripts = document.getElementsByTagName("script");
var src = scripts[scripts.length - 1].src;
var v = null;
if (/\?v=(.+)$/.test(src)){
v = RegExp.$1;
}
If it's the first script tag on the page, you can do something like:
var thescripttag = document.getElementsByTagName('script');
var v = thescripttag[0].src.replace(/^[^\?]+\??/,''); //gets everything after the '?'
If it's not the first script tag, you can change [0] to be whichever one it is, or try assigning an id to the script tag (untested).
You can find the appropriate script tag by looking for the desired filename and get the parameters off that .src URL.
function findScriptParams(fname) {
fname = "/" + fname + "?";
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var pos = scripts[i].src.indexOf(fname);
if (pos != -1) {
return(scripts[i].src.substr(pos + fname.length));
}
}
}
And then you would invoke it like this:
var params = findScriptParams("test_something.js");
if (params) {
// process the params here
}
Change it to
<script type="text/javascript"
src="include/javascript/test_something.php?v=1128557" />
Then create the script test_something.php to be
<?php
echo "var queryString='" . $_SERVER[`QUERY_STRING] . "'\n;";
?>
... rest of javascript here
You can even perform error checking/parsing of the query string using PHP or just get Javascript to do this.
You should do the following:
var scripts = document.getElementsByTagName('script');
var data = {};
for (var i = 0; i < scripts.length; i ++) {
if (!scripts[i].src) {
continue;
}
var value = scripts[i]..substring(scripts[i].indexOf('?') + 1);
var params = value.split('&');
for (var i = 0; i < params.length; i ++) {
params[i] = params[i].split('=');
data[params[i][0]] = params[i][1];
}
}
EDIT: Just incorporated some of the tips from others, and added them to my own answer.
JavaScript only has access to URL data for the page it's being executed on via window.location. It does not have access to any HTTP request variables passed to the javascript file itself unless the web server explicitly serializes it to JavaScript in the output.
One hack/workaround would be to find the script tag, get the src attribute, parse the URL and extract the GET parameters you need.
function getParamsFor(script) {
var params, anchor, paramArray, keyVal, tag, scripts;
scripts = document.getElementsByTagName("script");
// Make sure [].filter exists beforehand
tag = Array.prototype.filter.call(scripts, function (e) {
return e.src.indexOf(script) > -1;
})[0];
if (tag) {
anchor = document.createElement("a");
anchor.href = tag.src;
paramArray = anchor.search.substring(1).split('&');
params = {};
for(var i = 0; i < paramArray.length; i++) {
keyVal = paramArray[i].split('=');
params[unescape(keyVal[0])] = (typeof keyVal[1] != "undefined") ? unescape(keyVal[1]) : keyVal[1];
}
return params;
}
}
var o = getParamsFor("test_something.js");
o.v; // 112..

I want to attach custom ids to links based on query string

I want to attach custom ids to links based on query string and I found this very helpful post by Gregory (please take a look at it to get some context).
What I am trying to achieve is, if I go to www.mydomain.com, i require a default value to be added to the link on the webpage, example: www.ramdomdomain.com?myID1=default_value
I guess something must be edited after the if(hrefvalue==null) line in the code, but I can't figure out how to do it. Please help me. The following is the code I'm using:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function getHrefValue(key,url){
var query=new RegExp("[\\?&]"+(key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"))+"=([^&#]*)").exec(url);
return (query==null)?null:query[1];
}
function matchHrefs(){
var config={
'myid1':["#topnav a[href^='http://www.domain.com']"],
'myid2':["#topnav a[href^='http://www.domain.com']"]
}
for(var current in config){
var myvalue=getHrefValue(current,location.search);
if(myvalue!=null&&myvalue!=""){
$(config[current].join(',')).each(function(){
var href=$(this).attr('href');
var hrefvalue=getHrefValue(current,href);
if(hrefvalue==null){
var href_split=href.split('#');
$(this).attr('href',href_split[0]+(href_split[0].indexOf('?')>-1?'&':'?')+current+'='+myvalue+(typeof(href_split[1])!="undefined"?'#'+href_split[1]:''));
$(this).addClass('selected selected-'+current);
}
if(hrefvalue==""){
$(this).attr('href',href.replace(current+'=',current+'='+myvalue));
$(this).addClass('selected selected-'+current);
}
});
}
}
}
$(function(){matchHrefs();});
</script>
<div id="topnav">Random domain</div>
Is this what you're after:
<div>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>
<script type="text/javascript">
$(function() {
var requestid = new String(gup('myid'));
if (requestid == "") {
requestid = "unknown";
}
$("a").each(function() {
var href = $(this).attr("href");
href += "?myId=" + requestid;
$(this).attr("href", href);
})
})
//gup taken from here:http://www.netlobo.com/url_query_string_javascript.html
function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
</script>
<div id="topnav">
Random domain
Random domain
</div>
</div>

Categories

Resources