JavaScript behavior change depending on how page is loaded - javascript

I am having an issue where seemingly the way JavaScript executes is changing depending on whether I open a file from a brand new browser tab (copy-pasting the link in) versus if I open the page by clicking a link from another page.
A summarized version of my code is:
<html>
<head>
<script>
try {
// ...other code...
throw new Error("error");
} catch (e) {
location.href =
"https:\/\/google.com"; // would be "https:\/\/mysite.com"
}
window.close();
</script>
</head>
</html>
If I open this in a brand new tab by copy-pasting the link, the tab will navigate to https://google.com
However, if I open the link via a hyperlink, the new tab closes immediately.
Ideally, I want the redirect to be successful regardless of how the page is loaded.
Would love to understand what's going on here as the above code snippet is from an external library that I can't modify
Appreciate any insight or help!

From MDN:
This method can only be called on windows that were opened by a script using the Window.open() method, or on top-level windows that have a single history entry. If the window doesn't match these requirements, an error similar to this one appears in the console: Scripts may not close windows that were not opened by script.
In other words, a page opened by clicking a link on another site cannot use window.close(). However, if you create it with window.open(), that restriction does not apply and you can use window.close(), which is overriding your redirect. Ctrl clicking on a link to open it in a new tab also satisfies this condition. You can verify that by running window.close() in the devtools console and seeing whether or not it closes the tab.

Related

window.open with name - google 'search results' page behaves different

I have a series of links, which I want to open in a new window. Once a window is open and a new link is clicked it should reload the window with a new url.
It works fine by providing a specified target (name) to window.open for a series of websites, but somehow after the google search page has been opened it opens up another window.
When I click Open w3school and then Open React the behaviour is as intended. If I click Open google search and then another link it pops up in a new window.
Steps to recreate:
Click Open w3school opens a new window (intended)
Click Open React reloads the page in the opened window (intended)
Click Open google search reloads the page in the opened window (intended)
Click Open w3school opens a new window (not intended)
The code below illustrates the issue.
Does anyone have an explanation of this behaviour?
<html>
<body>
<p>Click the button to open a new browser window.</p>
<button onclick="openW3school()">Open w3school</button>
<button onclick="openGoogleSearch()">Open google search</button>
<button onclick="openReact()">Open React</button>
<script>
function openW3school() {
window.open("https://www.w3schools.com", "mywindow", "popup");
}
function openGoogleSearch() {
window.open("https://www.google.com/search?q=javascript", "mywindow", "popup");
}
function openReact() {
window.open("https://reactjs.org/", "mywindow", "popup");
}
</script>
</body>
</html>
Most probably it is due the fact that the Google search results page is sent with
cross-origin-opener-policy: same-origin-allow-popups; report-to="gws"
HTTP header (while the other two pages in your sample are not), what presumably tells browser "block ties with openers if they were on different domain (origin)".
According to Cross-Origin-Opener-Policy MDN page it should have the effect you describe for Google Chrome:
If a cross-origin document with COOP is opened in a new window, the opening document will not have a reference to it, and the window.opener property of the new window will be null.
It is strange that Firefox does not seem to respect that, although it is presented as compliant there.
One possible explanation would be that some script in the opened page changes its name (window.name).
You can verify / deny that if you check window.name of the "stray / detached" popup window in the console; if it will not be mywindow then you know the cause.
You may also check window.opener - if it is null, then it could indicate that given page deliberately broke ties with your page that created the popup.

Accessing other tabs/windows in a browser via JavaScript

I have a JavaScript application in a tab which opens if I click on a certain link on my page. If I click on the link again, I need to check if that tab is allready opened - if it is, then switch to that tab and do something, otherwise open a new tab.
Unfortunately using
var myApp = window.open("http://www.mypage.com/myapp.html", "My App");
if(myApp){
won't help me, because I can't rely on the URL, due to the fact that the URL will differ on each environment that I'm using.
How can I achieve this if I can't rely on the URL? The only thing I can check is the tab's name - it will allways be the same. How can I access the browser's tab array, please?
Thanks!
As far as I understand, you cannot access the browser's tab array (certainly not through JavaScript). This would be a security breach on the client side. You should think of each browser tab as a browser instance of it's own - unaware of any other tab.
You can track that if tab is opened already using the Cookie/Local storage.
Save the value "isOpened=true" in either Cookie or localStorage and Be sure to delete the values from the same when that tab is Closed or when user navigates to other pages using "onunload" event.
But the page you are going to open should be on the same Domain for accessing/ setting the Cookie.
Still we cannot do anything if the user opens the page by just copying the link.
as you are opening new window using javascript you can do this you can add a dummy attribute say "data-isOpend='no'" on that element
and when user click on that element you can change that attribute to "data-isOpened='yes'"and in javascript function before opening tha new window you have to check if data-isOpend=='no' then open link in new window else do nothing
(Just leaving a differenct ans here if any other dev comes here looking for solution for such prob,Just like me :) )
We can assign name to the tab while creating it
For eg.
function view_preview()
{
var abc;
if(abc!=null){
abc.close();
}
var url=some_link
abc=window.open(url,'tab_name');
}
Here, we are opening a new tab and if that tab is already opened we are 'refreshing' it.

preventing external page from redirecting MY (parent) page

Using the latest version of Chrome on Mac OS 10.7.
I assume it is some clever javascript that is enabling the folks at this webpage:
http://www.chairworks.com/
...to close my (the parent) page which opened their (chairworks.com) page in the first place.
I did not open them with javascript, but with an <a> tag with the target="_blank" attribute.
If I disable javascript, then the behavior stops.
www.chairworks.com
I would expect the page at chairworks.com/ to simply open in another tab/window... but what I find is that as soon as the new browser tab opens, it closes, and then my page (the parent tab/window) gets redirected to the chairworks.com page.
Kinda rude.
Can someone point me to what code enables them to do that? And how do I prevent it? (Assuming I want a link to behave as expected, such as in my demo page.)
I believe the proper thing to do is set corresponding link type attribute so the browser doesn't provide the target window with and opener reference.
Link
You can read more about link types here: https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types
This is the script they are using:
setTimeout('redirect_page()',0);
function redirect_page(){if (window.opener) { window.opener.location.href = '/home.html'; window.close(); } else { location.href = '/home.html'; }}
As to how to circumvent it (just an idea):
Create your own blank page, with it's source set to about:blank. When it loads (or after a time-out) you could write some code to that window that will then open the offending link.
Then the offending link just closes your buffer-page. F*ck 'm!! Power to the user!
Edit: looks like you could also name your page home.html hehe, but that is not such a workable solution..
Final Edit: SIMPLE LOGIC people...
www.chairworks.com
works for everyone, no javascript needed.
See this working jsfiddle example.
As #GitaarLAB explained, the targeted website is using the window.opener property to get access to your page. Using some Javascript yourself, and an about:blank page in the middle, can help you cut their access to your page. It would be like:
http://www.chairworks.com/
Some notes:
I'm leaving the href property there for users without JS enabled (guess what! the targeted website won't have JS neither! ;), or the web crawlers like search engines' (only those who don't care about JS stuff, though)
Before redirecting to the targeted website, you cut the back-link by resetting the window.opener attribute of the new window.
And after opening the targeted website, there's a return false; to prevent the normal the browser to use the href and target attributes.

How to put a window opened with window.open() behind the opener window?

I have a link that when clicked replaces the current page with another through the default <a> element click behaviour, but which also calls a JavaScript function to open another page in a new window. I would like the new window opened from my JavaScript function to appear behind the current window but can't figure out how to do this. In actual usage, I am feeding click thrus to a database, the link that is controlled by the window.open statement. The other link is to the clients site in a new window. I want the clients site to appear on top.
My current code is as follows:
<script language="JavaScript" type="text/JavaScript">
function countClicks(a,b)
{
window.open("http://stackoverflow.com?id="+a+"&id2="+b, "_blank");
}
</script>
test
So for the example URLs shown above I would like the (original) window with Google to appear in front of the new window with StackOverflow, but the new window always opens in front.
Try using window.focus() at the end of your existing function:
function countClicks(a,b) {
window.open("http://stackoverflow.com?id="+a+"&id2="+b, "_blank");
window.focus();
}
That should bring the existing window back to the front, noting that behaviour may vary between browsers and depending on popup-blocking settings, etc.
Or you could just swap the two urls, i.e., put the StackOverflow url in the href with the appropriate query string specified directly rather than in JS, and put the Google url in the window.open() call.
Popup behavior varies based on browser/user settings. I haven't been able to replicate the open behind behaviour myself, but I believe what you're looking for is .focus().
Try:
window.open("http://stackoverflow.com?id="+a+"&id2="+b, "_blank").focus();

close tab when a new site has loaded

I am wondering whether it's possible to close a tab as soon as a new site has loaded, without having to use js on the new site. I basically want to close the tab when we receive any content from the new site.
I use this to trigger a click event which submits a form:
$('#target_attack').click();
I tried putting window.close() right after this, but the tab closed without having loaded the new site.
I also tried to pause the script for 3 seconds and then close the tab, but for some reasons the site then won't load.
I also thought about using sessions but this means I would have to use js on the other site too, which I want to avoid.
I hope you guys can help a little javascript noob C:
Thanks in advance!
Guessing you are using window.open to open it in a new tab.
var winPop = window.open(url);
$(winPop.document).ready(function() {
window.close();
});
If javascript didn't open the window, javascript cannot close the window. Otherwise, window.close() is what you use.
You can try to bypass this security restriction (bad plan), but I do not believe this works on newer versions of any browser:
window.top.opener=null;
window.close();
See the docs - Firefox: https://developer.mozilla.org/En/DOM:window.close, IE: http://msdn.microsoft.com/en-us/library/ms536367%28VS.85%29.aspx

Categories