How to check location.href is completed? - javascript

I want open a window and then does something after it finishes loading, is there an easy way to do this?
my current code is something like:
cur_window = window.open( 'http://www.google.com' )
// does something when cur_window finishes loading
thanks

The only way to do this is if you write code in the page which is opened in the popup to tell the parent page, the opener object in js, that it has finished loading.
In your example, as your are loading Google, this is not possible.

Assuming you're accessing pages within the Same Origin...
the "easy way" isn't as responsive as jQuery's ready event which can't be applied outside of the original window context:
cur_window.onload = function () {
//new window has loaded
};
If you're trying to open http://www.google.com/ in a new window, you wont have any access to the window object, and therefor have no way of knowing when the new window has loaded.

Related

How a page can be determined if it's loaded

I'm going to use postMessage method to send a text to an opened window right after opening the window on ther origin.
I tried the following:
let ref = window.open("<address>", "name", "resizable,scrollbars,status");
ref.postMessage("Some Message");
A listener is defined on the other page to get the posted message, but it doesn't work, since the posted message is being sent before the page loading is completed.
Is there any way to check that the page on the opened window is fully loaded?
You can implement an "handshake" mechanism, so it would be like,
parent adds an event listener to catch child messages (window.addEventListener('message', () => {}))
parent opens child window
child window sends "I'm a live" message to parent (parent.window.opener.postMessage('ImALive', '<url address of parent>'))
parent sends it's data to child
Something like that.
You can try simple Javascript trick as below to see if DOM is loaded, you can use this function which will get execute after DOM gets load.
document.addEventListener('DOMContentLoaded', function(event) {
//alert("hello"); your code
})
Have you tried $(window).load(function(){}).
You can write your code in this event and then try it.
This question on SO might help.

Call JavaScript of parent window from child window

I have a calendar and when I click on a <td>, a pop-up window appears so you can create your evenement for the date you selected. I want to add a feature.
When the user finishes creating the event, I want to send a JavaScript request to the parent page so I can refresh the calendar using AJAX. Basically, I want to call a function from the child, but the function is on the parent page.
On Google, I only found a script that can refresh the parent window – nothing about a “parent callback”. ☹ Is it even possible?
P.S. The answer can be pure JS or jQuery, it doesn’t matter. I’ll keep looking in the meanwhile.
What you're looking for is a reference to the window that opened the popup window. Once you have that, you can call functions in that window, read and write variables in that window, or even manipulate its DOM.
That reference is called opener. It gives you the window object for the window that opened the current window. For example, if you have a function in the original window like this:
function updateMe( data ) {
alert( data );
}
then in the popup window you could call it like this:
opener.updateMe( 'Hello!' );
Naturally, you need to make sure that updateMe() is a global function in the original page. Or if you have some object in the original page and updateMe() is a method of that object, you can still do it, as long as the object is global. e.g. in the host page:
var myObject = {
updateMe: function( data ) {
alert( data );
}
};
then in the popup you could do:
opener.myObject.updateMe( 'Hello!' );
Basically, as long as you could get to the object or function in the original page with window.whatever, then in the popup you can simply change that to opener.whatever.

Is there a way to have an onload callback after changing window.location.href?

Essentially what I'd like to do is something to the effect of this:
window.location.href = "some_location";
window.onload = function() {
alert("I'm the new location and I'm loaded!");
};
Is there any way to have a callback when the window's new location is loaded? (The above code doesn't work.)
No, you cannot do it the way you want. Loading a new page closes the current document and starts loading a new document. Any code in your current document will no longer be active when the new page starts to load.
To have an event handler when the new document loads, you would either need to insert code into the new page's document or load the new document into an iframe and monitor the loading of the iframe from your current document.
Setting window.location.href to a new value tells the browser to simply go to the next page.
Like so:
window.location.href = "http://www.google.com/";
Once the browser goes to google.com, that's it, your Javascript is no longer executing, and there is no way for you to have any sort of callback, because the browser is no longer running your page.
So, the answer is no.
in regards to callback and js execution in new context - no (as per orig answer), but there are ways to access loaded elements without callback. For e.g. scrollIntoView on a loaded element, you can append the selector:
const href = '#someElem'
if(window.location.pathname !== '/') window.location.href = `/${href}`
else document.querySelector(href).scrollIntoView()

Access a window by window name

If I open a window using
window.open('myurl.html', 'windowname', 'width=100,height=100');
How do I refer to the new window (from the same page that opened it) using 'windowname'? This question is specifically about this. I'm aware that I could save a reference to the handle by using "var mywin = window.open(...)" but I don't care about that in this situation.
Thanks, - Dave
In firefox (might work in other browsers too, but now it's not my concern) I was able to reference one window accross multiple page loads with
var w = window.open("", "nameofwindow");
This opens new window if it doesn't exist and return reference to existing window if it does exist without changing contents of the window.
With jQuery I was then able to append new content, to make quick collection of interresting links like this
$('body', w.document).append(link_tag);
If you didn't save a reference to the window then there is no way to restore it. However, if that window is still open and if the page loaded there belongs to the same domain as your page, you can run JavaScript code in it:
window.open("javascript:doSomething()", "windowname");
Whether that's sufficient in your scenario depends on what you are trying to achieve.
Petr is correct:
var w = window.open("", "nameofwindow");
works in all browsers, I am using it to retrieve the reference to the window object previously opened by a different page. The only problem is the initial opening of the page, if the popup does not exist, you will get a new window with a blank page.
I tried invoking a Javascript function inside the context of the other document in order to check whether I opened a new window or retrieved the already active page. If the check fails, I just invoke window.open again to actually load my popup content:
var w = window.open("http://mydomain.com/myPopup", "nameofwindow");
Hope that helps.
It is not possible. The windowName is just to be used in target="..." of links/forms or to use the same name again in another window.open call to open a new url in that window.
Try open that window with the name, but URL is '' again, to check if it's a blank window or not. If it's in open, then you will get the window; if not, a new window open, and you need close it.
Add the children in localStorage will help to prevent to open the new blank window.
Please check my code in https://github.com/goldentom66/ParentChildWindow
Sorry I am posting late, but if you still have the other window open, and they are on the same domain, you can run, on the first window:
function getReference(w) {
console.log('Hello from', w);
}
And on the second window:
window.opener.getReference(window);
afaik there's no way like windows['windowname'].
The 'windowname' assigned in window.open() can be addressed as a target in <a target="windowname" [...] >

Using JQuery to open a popup window and print

A while back I created a lightbox plugin using jQuery that would load a url specified in a link into a lightbox. The code is really simple:
$('.readmore').each(function(i){
$(this).popup();
});
and the link would look like this:
<a class='readmore' href='view-details.php?Id=11'>TJ Kirchner</a>
The plugin could also accept arguments for width, height, a different url, and more data to pass through.
The problem I'm facing right now is printing the lightbox. I set it up so that the lightbox has a print button at the top of the box. That link would open up a new window and print that window. This is all being controlled by the lightbox plugin. Here's what that code looks like:
$('.printBtn').bind('click',function() {
var url = options.url + ( ( options.url.indexOf('?') < 0 && options.data != "" ) ? '?' : '&' ) + options.data;
var thePopup = window.open( url, "Member Listing", "menubar=0,location=0,height=700,width=700" );
thePopup.print();
});
The problem is the script doesn't seem to be waiting until the window loads. It wants to print the moment the window appears. As a result, if I click "cancel" to the print dialog box, it'll popup again and again until the window loads. The first time I tried printing I got a blank page. That might be because the window didn't finish load.
I need to find a way to alter the previous code block to wait until the window loads and then print. I feel like there should be an easy way to do this, but I haven't found it yet. Either that, or I need to find a better way to open a popup window and print from the lightbox script in the parent window, without alternating the webpage code in the popup window.
You should put the print function in your view-details.php file and call it once the file is loaded, by either using
<body onload="window.print()">
or
$(document).ready(function () {
window.print();
});
Got it! I found an idea here
http://www.mail-archive.com/discuss#jquery.com/msg18410.html
In this example, they loaded a blank popup window into an object, cloned the contents of the element to be displayed, and appended it to the body of the object. Since I already knew what the contents of view-details (or any page I load in the lightbox), I just had to clone that content instead and load it into an object. Then, I just needed to print that object. The final outcome looks like this:
$('.printBtn').bind('click',function() {
var thePopup = window.open( '', "Customer Listing", "menubar=0,location=0,height=700,width=700" );
$('#popup-content').clone().appendTo( thePopup.document.body );
thePopup.print();
});
I had one small drawback in that the style sheet I was using in view-details.php was using a relative link. I had to change it to an absolute link. The reason being that the window didn't have a URL associated with it, so it had no relative position to draw on.
Works in Firefox. I need to test it in some other major browsers too.
I don't know how well this solution works when you're dealing with images, videos, or other process intensive solutions. Although, it works pretty well in my case, since I'm just loading tables and text values.
Thanks for the input! You gave me some ideas of how to get around this.
Are you sure you can't alter the HTML in the popup window?
If you can, add a <script> tag at the end of the popup's HTML, and call window.print() inside it. Then it won't be called until the HTML has loaded.

Categories