i have aspx pages with vb.net in the back. I need to use javascript to open a new window on page load. I am also sending a querystring (www.mysite.com/default.aspx?dest=register.aspx) from the previous page. I need the javascript to parse the querystring and open the new window only if the URL has a querystring. please advice
For parsing the URL it is handy to use some kind of a javascript library, e.g. prototype ;)
The code would look something like
var str = "http://www.mysite.com/default.aspx?dest=register.aspx";
var obj = str.parseQuery();
if(obj.dest) window.open(obj.dest);
To use prototype, all you have to do is download the javascript file here and include it in your page with the script tag ;)
You could put the code into the onload event handler, but be aware of security restrictions noted by stefpet. If you want to just redirect to the page then you can do it in the codebehind. If you really want it on load, then you need something like
ClientScript.RegisterClientScriptBlock(GetType(), "load_redirect", your_js_code , false);
where you replace your_js_code with the actual code.
Are you looking for the querystring "dest" specifically?
Then this would do:
if(location.href.indexOf('?dest=') >= 0)
window.open('myurl', '', '');
Do you want to use the value of the querystring to determine what page to open? In that case you might be better off generating the script with some serverside code:
window.open('<%=Request.QueryString("dest")%>', '', '');
You could do it in all-javascript as well. There are libraries out there that'll help you parse querystrings, but the quick and dirty way would be:
if(location.href.indexOf('?dest=') >= 0) {
var dest = location.href.substring(location.href.indexOf('?dest=')+6);
window.open(dest, '', '');
}
"Quick and dirty" being the operative term here. Notice that I'm only looking for ?dest
, i.e. url's that have "dest" as the first querystring. I also don't check whether there's an ampersand in the value, so it even requires that "dest" is the only querystring. You can be as elaborate as you want to make it more reliable but as I said, a) you should generate this script with serverside code, b) you should use an existing parser library if you really don't want to go with a.
Please note that unless you run this where you are aware that the browsers allow this this will not work because the window.open call will be blocked by the browsers popup-blocker.
To open a window without being blocked the invokation must originate from an explicit user event (i.e. "click").