open a new window, and call javascript function - javascript

I am new to javascript. I would like to know how a new window can be opened from a javascript method, and then call it's javascript methods.
The url of the window, is in another domain (can cause a security problem !?), and I don't have control over it.
For example, a code that should behave as the followings:
handler<-openAWindow("www.someurl.com");//open a window and get a handler for it
handler->someMethod1(param1, param2);//call some javascript method
handler->someMethod2(param3, param4);//call some other javascript method<br>
Thanks,
Eran.

You cannot control or access a cross domain window unfortunately. This is done for security precautions. Do you have control over the other URL?
However, if the window is on the same domain you do have access to the window and its DOM.
var win = window.open("/page", "title");
win.someFunction();
var el = win.document.getElementById("id123");
//etc.

Related

JavaScript: Open new tab and detect URL change

I am trying to open a new window with a URL for oAuth, however I cannot add any event listener.
const wind = window.open(msg.data.url);
console.log(wind);
wind.onload = function () {
wind.onpopstate = function (e) {
console.log('pop', e);
};
};
It just does nothing. However it turned out that window.open() has given me a not full window object. And that is all what I have got. How do I add event listener for that?
According to the MDN web docs regarding the window.open() function:
The returned Window reference can be used to access properties and
methods of the new window as long as it complies with Same-origin
policy security requirements.
That means if you call window.open("/questions") in a terminal on this webpage, you get a full window object, but if you call window.open("https://google.com"), it returns only a simplified object on which you will not be able to add event listeners. This is to prevent cross-origin attacks. You may, however, transfer data to the new window object via Window.postMessage(), if the new window is listening for that type of event. See here for more information on that.

Restore native Window method

For a script I'm writing, I'd like to use the native window.open method. However, a script already loaded to which I don't have access, overwrites the global window.open method with a boolean (ouch).
I know how to restore the methods on the Document (via HTMLDocument.prototype), but I don't know how to restore them on the Window, as I can't seem to find the equivalent for that to Window. Window.prototype.open does not exist for example.
I have tried creating an iframe, and getting the open method from that contentWindow in the iframe, but the browser will block opening windows using open because it was probably created in another origin. Neither delete open; does work because open was defined using var in the globally loaded script.
So, how can I restore the open method, defined as 'native code' in Chrome?
I know there are similar questions around, but actually the main question is:
Is there a equivalent of HTMLDocument for the Window object?
I've found this question and the accepted answer (using an iframe) could be used in your case.
The only issue is you can only use the retrieved version of window.open as long as the iframe is still in your document.
function customOpen() {
// local variables definitions :
var url = "https://stackoverflow.com", iframe, _window;
// creating an iframe and getting its version of window.open :
iframe = document.createElement("iframe");
document.documentElement.appendChild(iframe);
_window = iframe.contentWindow;
// storing it in our window object
window.nativeOpen = _window.open;
try {
window.open(url);
} catch (e) {
console.warn(e); // checking that window.open is still broken
}
window.nativeOpen(url);
// deleting the iframe :
document.documentElement.removeChild(iframe);
}
document.getElementById("button").addEventListener("click", customOpen);
Another JSFiddle
Keeping the workaround answer in case someone needs it :
Can you execute a custom script prior to the execution of the script that redefines window.open? If so, you could create a copy of the window.open in another global variable.
It could look like this :
1. First : a backup script
window.nativeOpen = window.open;
2. Then, whatever the window.open overwriting script does :
window.open = false; // who does that, seriously?
3. Your window opening script, that'll use your window.open copy :
function customOpen() {
var url = "https://stackoverflow.com";
try {
window.open(url);
} catch (e) {
console.warn(e);
}
window.nativeOpen(url);
}
JSFiddle example

How do I navigate to bing.com and enter a search text using the chrome console?

Below is my code.
It is resulting in unexpected behaviour.
It navigates to bing.com but it does not fill in the text field. Also, I have noticed that the console get cleared after navigating to a new webpage.
window.location = "https://www.bing.com";
window.onload = function(){
var editSearch = document.getElementById("sb_form_q");
editSearch.value = "Quux";
}
You are binding the onload function to the existing window object.
When the browser loads the new page, it will make a new window object which won't have your property set on it.
JavaScript run in one page (even when you are running it through developer tools) can't persist variables onto a different page.
(Storage mechanisms like localStorage and cookies are available, but you would need code in the subsequent page to look for them).
JavaScript is only valid for the current page you are on. When you are executing code from DevTools console, you are executing code on that page itself. So, when you navigate to another page using window.location you loose the onload handler you have defined.
To add handlers to a different page, it must be connected to your page (the parent) in some way, like an iframe or a popup.
ifrm = document.getElementById('frame');
ifrm.src = 'http://example.com';
ifrm.contentWindow.onload = function () {
// do something here with
// ifrm.contentWindow.document.getElementById('form')
}
As #Quentin said.
But you can do another way like ..
var keyword = "Quux";
window.location = "https://www.bing.com/search?q="+keyword;

Refresh external browser window in node-webkit

I'm trying to load a file in the browser and then refresh it when an event is fired. I'm using the node-open module:
var open = require('open');
var url = 'http://www.stackoverflow.com';
var myWindow = open(url); //returns a child process
myWindow.on('refresh', function() {
open(url);
});
// stuff...
myWindow.emit('refresh');
The open() method returns a child process, so I'm attaching an event listener to it that is triggered when the refresh event is fired. However (as you can see) a new window is opened when refresh is fired. How can I keep track of the original window and refresh it?
If you really mean an external browser, then I'm not sure, but if you're using the window.open in node-wekbit, you could do this:
var url = 'http://www.stackoverflow.com';
var myWindow = open(url); // returns a Window object
. . .
myWindow.window.location.reload();
This will open another node-webkit window with the given url, but beware that it's not as safe to browse with node-webkit as with a standard browser as not all of the security protections are in place.
If you're talking about an external browser, then I'm not sure there is an easy solution. I don't think there's a signal you can send a child process to cause a browser reload.

JavaScript - Reference Browser Window by name? [duplicate]

This question already has answers here:
Access a window by window name
(7 answers)
Closed 4 years ago.
When you create a new browser window, you pass it a name like this:
myWindow = window.open('http://www.google.com', "googleWindow");
Later you can access the window from the variable you saved it as:
myWindow.close();
Is it possible to access and manipulate a window by it's name (googleWindow) instead of the variable?
If it is not possible, what is the point giving windows names?
No. Without a reference to the window, you can't find it again, by name or otherwise. There is no collection of windows.
UPDATE: Here's how you could do it yourself:
var windows = {};
function openWindow(url, name, features) {
windows[name] = window.open(url, name, features);
return windows[name];
}
Now, openWindow will always open the window, and if the window already exists, it will load the given URL in that window and return a reference to that window. Now you can also implement findWindow:
function findWindow(name) {
return windows[name];
}
Which will return the window if it exists, or undefined.
You should also have closeWindow, so you don't keep references to windows that you opened yourself:
function closeWindow(name) {
var window = windows[name];
if(window) {
window.close();
delete windows[name];
}
}
If it is not possible, what is the point giving windows names?
The name is used internally by the browser to manage windows. If you call window.open with the same name, it won't open a new window but instead load the URL into the previously opened window. There are a few more things, from MDN window.open():
If a window with the name strWindowName already exists, then strUrl is loaded into the existing window. In this case the return value of the method is the existing window and strWindowFeatures is ignored. Providing an empty string for strUrl is a way to get a reference to an open window by its name without changing the window's location. To open a new window on every call of window.open(), use the special value _blank for strWindowName.
Linus G Thiel says that you cannot do this in javascript. Oddly enough, his answer lists an excerpt from MDN that sounds like it tells how to do this. The line was:
"Providing an empty string for strUrl is a way to get a reference to
an open window by its name without changing the window's location."
I tried this and it works for me.
winref = window.open('', 'thatname', '', true);
winref.close();
However, this may only work if you opened the window from your page. And if that's true, then it's kind of pointless to do a window.open just to get the reference. You probably already have the reference, in that case.
Mark Goldfain's solution no longer works as written as of 9/8/2015
As per this w3 specification,
If the first argument is the empty string, then the url argument must
be interpreted as "about:blank".
I believe this is a difference between HTML4 and HTML5.
IE and Chrome have updated this behavior to match this specification, while Mark's solution still works on FF (though I imagine that they'll fix this soon). A few weeks ago this worked on all major browsers.
My particular problem involved window control while navigating, where the chat window opening is black boxed as well as most of the code on the page - redefining window.open was right out. My solution involved calling the blank window with the reference before calling the function which called the chat window. When the user navigated away from the page, I was able to rely on the fact that windows other than the original parent are not allowed to modify the child window, and so I was able to use Mark Goldfain's solution unchanged.
The solution provided by Mark Goldfain can be edited to work with the new browsers, at least to open a window and keep a reference to it between page refresh.
var winref = window.open('', 'MyWindowName', '', true);
if(winref.location.href === 'about:blank'){
winref.location.href = 'http://example.com';
}
or in function format
function openOnce(url, target){
// open a blank "target" window
// or get the reference to the existing "target" window
var winref = window.open('', target, '', true);
// if the "target" window was just opened, change its url
if(winref.location.href === 'about:blank'){
winref.location.href = url;
}
return winref;
}
openOnce('http://example.com', 'MyWindowName');
I ended up using the following:
var newwindows = {};
function popitup(url, nm) {
if ((newwindows[nm] == null) || (newwindows[nm].closed)) {
newwindows[nm] = window.open(url, nm, 'width=1200,height=650,scrollbars=yes,resizable=yes');
}
newwindows[nm].focus();
}
then referenced using:
<button type="button" onclick="popitup('url/link.aspx?a=bc',this.value)" value="uniqueName">New</button>

Categories

Resources