window.location.href inserts new page inside of current page - javascript

New to JavaScript. I have an AJAX function that ultimately is intended to navigate to a new URL. However, instead of the new page appearing as if the user had typed the URL themselves, the new page is sort of 'inserte' inside the same div of the button that launched the script via its onclick handler. The line in question is this:
window.location.href("newpage.html");
What I want is the old page to be replaced by the new page and the old page to be retained in the browsing history.
Note that this script is called by a button inside of a form. I can show the whole code if it is helpful.
Thanks!

It's usually used as follows:
window.location.href = "newpage.html"
href is NOT a function, but a property.
References:
https://developer.mozilla.org/en-US/docs/Web/API/window.location
I think you may have been confused with window.location.assign("http://whatever") method
Caveat: href(url) may work on some browsers (IE???), but definitely not in FireFox - it gives an explicit "Not a function" error when run via JS-Execute

Related

Browser back-button displays the preserved page state sent by server but any DOM modifications done using javascript is not getting preserved

The code snippet (in C#) that is used to trigger the JavaScript code from code-behind is as:
int returnValue = SaveStudent("John", "XII"); // SaveStudent() is a C# function that saves the student details in DB and returns studentId.
hdnStudentId = returnValue ; // hdnStudentId is a hidden-field control
ScriptManager.RegisterStartupScript(this, this.GetType(),
"ShowStudent", "showStudentDetails();",true);
The definition of "showStudentDetails()" JavaScript method is as:
function showStudentDetails(){
If($('[id*=hdnStudentId]').val() > 0){
// show the popup
}
}
Here is the description of the issue:
In a web-page 'WebPage1.APSX', after saving the data in DB, I display
a bootstrap popup using ScriptManager Class (as mentioned above).
Here I set the value of a hidden-field variable to the inserted rowid
that is inserted in DB(say 12345) .
The ScriptManager class
successfully registers the script in DOM and displays the popup.
Thereafter I reset the Here hidden-field variable to -1. In the
popup, I have a button control that redirects to another page
'WebPage1.APSX'.
$('[id*=hdnStudentId]').val('-1');
Now user clicks on 'browser back-button', it doesn't hit the server-side code and
renders the UI based on previous instance of page sent by server.
As this is previous instance of page sent by server, hidden-field
variable gets set to '12345' instead of -1 (not sure why, we already
did reset the value to -1) and display the popup again.
Requirement: When user clicks on 'browser back-button', we need to remember the previously manipulated data in DOM as well(i.e. $('[id*=hdnStudentId]').val('-1');) so that we can avoid to display the popup on browser back-button click.
You need to checkout Browser history API to save your page state in the history when no server involved, here is mdn doc https://developer.mozilla.org/en-US/docs/Web/API/History_API
The DOM window object provides access to the browser's history through
the history object. It exposes useful methods and properties that let
you move back and forth through the user's history, as well as --
starting with HTML5 -- manipulate the contents of the history stack
and also an example of Ajax navigation https://developer.mozilla.org/en-US/docs/Web/API/History_API/Example. hope that helps!
Thanks #Salus .. I followed your advise.. And finally the following code-snippet worked for me..
I used 'history.pushState();' method just after showing the popup:
$('#divStudentDetails').modal('show');
history.pushState(null, null, "");

Is there a way to find the window of the previous page (other tab)?

If you open a link in a new tab (with MMB or right click or preferred method, however), is there a way from the new tab window to find the opener window? These don't work:
window.opener
window.parent
Maybe it's just not possible, since following a link usually 'overwrites' the window, so no ref is possible, but since we have tabs... maybe... a ref IS possible?
I want the opened window to do a postMessage to the original window to let it know the page has loaded, so the original window can update the link style.
I don't make these pages, so I don't have access to the back-end or HTML printage. Think Greasemonkey: I add JS to existing websites to improve them.
The only thing I can think of is intercepting the click event, grabbing the URL, and passing it to window.open and subsequent postMessage calls on the returned window object. Do you generate the page with these links?
In some browsers window.open(url,'_blank') will open in a tab.
I think there is two solutions to your problem
First solution : Cookies
An easy way is to set a cookie with the value of the current page everytime a link is clicked, you can use a library like this one to set a cookie and get it in the next page once you click like this
$("a").click( function () {
$.setCookie("currentPage",document.URL);
});
In the next page you just get the cookie like this
if($.getCookie("currentPage") != undefined )
var previousPage = $.getCookie("currentPage");
Second solution : Server-side langage
If you're using a server side langage like php, it's easy to get the url of the previous page :
<?php
if (isset($_SERVER['HTTP_REFERER']))
echo "<script> var previousPage='" . $_SERVER['HTTP_REFERER'] . "'; </script>";
?>
And finally, to post a message you just need to test if the previousPage variable is set:
if(previousPage != undefined)
{
// Code to post your message
}

passing different variables to same page

I am trying to build a web app mainly using html and javascript. I use a number of different variables in the app that are passed through the url.
here are the problems, I have some links that link to the page the app is currently on, just with changed variables, but while clicking on the links does change the url value, the page does not change/reload for the new values when using and an href, is there a clean way to force the page to reload if you link to the current page, or change the url?
currently I am using jQuery to set the window.location with the new variables then reloading the page.
also, I have a similar problem for using the back button on the browser. It will change the url but not refresh the page, so if you have a variable set to 1 you change it to be 2, that works and the page will reload with the variable set o 2, but if you go back using the browser history the url will say that your variable should be 1, but the rest of the page will still act like the variable is 2, until you refresh the page.
is there someway to set a page so that the it will automatically refresh when you go to the page from the same page, either through links or going forward or backward with the browser history?
as per request here is part of the parts of the code I am having problems with:
first is the code for the creating the html elements onload
var sel_tags=document.getElementsByName("selected_tags")[0];
var temp="";
if(Tags==null)
{
temp="\<p>All Notes\<\/p>";
}
else//Tags not empty, and there are tag filters
{
var click= new Array("",a+ AtTagShow);
var GoTo="PageViewNotes.html?"
for (var i=0; i < Tags.length; i++) {
//if we are showing #tags, or a tag is not an #tag
if(AtTagShow||Tags[i][0]!="#")
{
click[0]=t+Tags[i];
if (temp.length>0)
{temp+="\<span class=\"spacer\">\/<\/span>"};
temp+="\<a class=\"selected_tags_label\""+
"href=\""+GoTo+click.join("&")+"\">\<span>"
+Tags[i]+"\<\/span>\<\/a>"
}
};
};
sel_tags.innerHTML=temp;
here is the jquery code for setting the onclick:
$(".selected_tags_label").live("click",function(){
window.location=(this.href);
window.location.reload();
});
an example url for this issue would be:
page.html?Tags=#rediculous,#meeting&AtTagShow=true
by clicking on the rediculous element the url would change to:
page.html?Tags=#rediculous&AtTagShow=true
window.location.href="page.html?Tags=#rediculous&AtTagShow=true"
Take a look at the jQuery History plug-in for setting your site up to have back / forward history. It helps with setting up states on your page, that call data based on what query parameters are in the URL string.
In modern browsers (IE8+, Opera 10.6+, Fx 3.6+, Safari 5+) you have hashchange event.
Instead of reloading page, maybe you can achieve desired results with something like this:
<script>
document.onhashchange = function(){
// do something
}
</script>
MDN might be also helpful.
If you are using query parameters (things after the ? mark in the URL), then changing a query parameter and setting window.location to that new URL should cause a new page load from the server.
If you are using hash values (things after the # mark int he URL), then changing the hash value will not cause a new page load.
So, if you want a fresh page load from server each time you change a value, then you should be using query parameters. Back and forward should also work fine when using query parameters.
If you're purposely trying to do all of this with hash values to avoid an actual server page reload, then you will have to do more coding to intercept hash changes and process them. That is easier to do in modern browsers than older browsers using the window.onhashchange event. See this page on MDN for more info.
Browser reloads the page, whenever any of these parts of the URL are updated via window.location:
Domain
Port
Path
Query string
But it won't load the current document, if you change the fragment_id part (which is simply a reference to an HTML element inside the current document).
Thus from what you say, I guess you're updating the fragment id.
Also this might help to know that window.location.reload() method does the work of F5 key.

Problems using window.opener

I have a simple ajax application
From this, a popup is launched, with a form.
Both the form resultpage, and the ajax application hava a javascript file in common.
From the popup window, in the form resultpage, I am trying to call a method from the common javascript file, to apply to the parent window.
My javascript file contains an updateLayer method, which when caleld from the parent window, works fine. I get nothing when trying to call it from the popup window.
The resultpage in the popup window has
<script type="text/javascript" src="x.js">window.opener.updateLayer("Layer3", "380118179930"); </script>
before any html.
Nothing happens in the parentwindow. I have also tried window.parent.
What is the reason and solution for/to this?
I assume this is related to this question, asked by another user that also happens to be named Josh.
In my answer to that question, I tried to explain that the functions from a Javascript file included in your parent window would be attached to the window object, so you use window.opener to get access to that window object to call them.
It looks like you've almost got this solved, but the problem here is that by including src="x.js" in the script tag from your form response, you're effectively overwriting any code placed inside the script. Plus, since x.js is included in the parent window, there's no need to have it in the popup at all, anyway.
The code for your form response should look like this:
<script type="text/javascript">
window.opener.updateLayer("Layer3", "380118179930");
</script>
I've removed the src="x.js" attribute, which would otherwise prevent code between the <script></script> tags from being executed.
Your problem can be that you have two JavaScript files with the same content, while no namespaces are applied.
First, your parent includes the file.js where your updateLayer() is defined. Then the parent opens the child window, which also includes that file.js. If you do that, you have two threads running, where each of them may have it's own functions and objects without bothering the other. I assume that your function is global. This can cause problems, if no namespaces are used. Also it can happen that your big ajax library creates iframes and things like that, and you won't see anything from that because it happens under the hood.
So try: top.window.opener.updateLayer("Layer3", "380118179930");
If that doesn't help, try to open a blank window with no included file.js and call that function from the opener. If that works, wrap the contents of that file.js in a namespace like myNamespace = {....big file content inbetween....}, make two versions of that (or better dynamically include the content) and make sure you have two different namespace. JavaScript is most often not working the way you think it should.
Also, make very sure that the url for your opened window has exactly the same domain. It can cause security issues so that the browser disallows access from a child window to it's parent.
Josh,
Can you determine if the function is triggered at all, like annakata suggests? E.g. by putting an alert box on the first line of the function?
Otherwise: how is the function updateLayer defined in x.js?
If it's defined like this:
function updateLayer(layer, result) {
// ...
}
...then it should work fine.
If it's defined as follows:
var updateLayer = function(layer, result) {
// ...
}
then it will not be available as property of the window object (and thus not available as property of window.opener either). In Firefox, at least; I haven't tested this in IE or other browsers.
Edit: why is this question tagged 'ajax'? AFAICS, all of the problem resides on the client side of the application; no ajax is involved.
Try following:
parent.window.updateLayer();
in a separate <script> tag.
I'm not quite sure whether it works with both src=some.js and inline script at the same time.
Since you have given the script element a src attribute, the results of x.js will be parsed as JS and the text content of the element will be ignored.
<script type="text/javascript" src="x.js"></script>
<script type="text/javascript">
window.opener.updateLayer("Layer3", "380118179930");
</script>
Create a new updateLayer function in you parent html file. Rename it different and call the original updateLayer from it.
e.g.
function updateLayerPage(arg1, arg2)
{
updateLayer(arg1, arg2);
}
and then call this new function from the child page
window.opener.updateLayerPage("Layer3", "380118179930");

Why does my event handler cause an "is not a function" error, but works from the Firebug console?

Using JQuery 1.2.6, testing from Firefox 3 and IE7. I have a very basic bit of JavaScript to reload a captcha image. In my JS file, I have:
var Captcha = {
count: 0,
Refresh: function(){
// Concatenate "count" to force a URL change, which forces the browser to reload the image
$('#Captcha').attr('src', 'Captcha.aspx?' + Captcha.count);
Captcha.count++;
}
}
My link looks as follows:
Try a different image
When I click on the link, I get a JavaScript error. From the Firebug plugin for Firefox, it says "Captcha.Refresh" is not a function. So, I go to my Firebug console in the same window, and type
Captcha
And I get an "object" in the response line (as expected). I then type
Captcah.Refresh
And I get a function() in the response line (as expected). I then type
Captcha.Refresh()
And it executes the function, updates my captcha image, everything is dandy. If I go back and try the link again, it still does not work. If I type in Capcha.Refresh() into the console without ever hitting the link, it also works fine. What on earth am I missing here? Clearly the JS is getting loaded, but why doesn't that function call work?
The problem arises because you have an element with an id of Captcha, and a global variable with the same name. IE traditionally introduces a global variable for every id attribute. FF doesn't... but pretends it does in certain situations for compatibility with IE. In this case, the click handler sees Captcha as an element rather than your object.
Work-arounds:
Change the id of the Captcha element.
Or, change the name of your global object to something other than Captcha.
Or, use Pim Jager's technique to move interpretation of the handler into a context where the global Captcha variable has been overwritten with your own.
Or, change your onclick attribute to:
onclick="window.Captcha.Refresh();"
...this will force lookup of the Captcha property in the context where it has been replaced by your global variable.
(all of these tested in IE6 and FF3 - i recommend Pim Jager's answer)
Try sepperating the HTML and javascript:
$('#ChangeCaptcha').click(Captcha.Refresh);

Categories

Resources