I use window.open to populate a new window with varying content. Mostly reports and stored HTML from automated processes.
I have noticed some very inconsistent behavior with Chrome with respect to window.open().
Some of my calls will create a new tab (preferred behavior) and some cause popups.
var w = window.open('','_new');
w.document.write(page_content);
page_content is just regular HTML from AJAX calls. Reports contain some information in the header like title, favicon, and some style sheets.
In IE9 the code does cause a new tab instead of a pop-up, while Chrome flatly refuses to show the content in question in a new tab. Since the content is sensitive business data I cannot post it here. I'll answer questions if I can.
I know some people will say this is behavior left up to the user, but this is an internal business platform. We don't have time to train all the users on how to manage popups, and we just need it to be in a new tab. Heck, even a new window would be preferable to the popup since you cannot dock a popup in Chrome. Not to mention none of the popup blocking code would affect it.
Appreciate any insight.
window.open must be called within a callback which is triggered by a user action (example onclick) for the page to open in a new tab instead of a window.
Example:
$("a.runReport").click(function(evt) {
// open a popup within the click handler
// this should open in a new tab
var popup = window.open("about:blank", "myPopup");
//do some ajax calls
$.get("/run/the/report", function(result) {
// now write to the popup
popup.document.write(result.page_content);
// or change the location
// popup.location = 'someOtherPage.html';
});
});
You can try this:
open a new tab please
<script>
function openWindow(){
var w = window.open("about:blank");
w.document.write("heheh new page opened");
}
</script>
Is very easy, in order to force Chrome to open in a new tab, use the onmouseup event
onmouseup="switchMenu(event);"
I have tried this and it worked fine in chrome. If opening a new tab is on a user action(such as a mouse click) this will work fine without any issues. But if the code is executed in another script block, you may need to enable pop-ups in chrome. Looks like this is to handle all the click-bait sites.
let newTab = window.open('', '_blank');
if (this.viewerTab == null) {
console.log("opening in new tab to work, pop-ups should be enabled.");
return;
}
................
newTab.location.href = viewerUrl;
window.open('page.html', '_newtab');
Specify the '_newtab'. This works in IE and FF, and should work in Chrome. But if the user has things configured to not open in new tab then not much you can do.
Related
I want to create a link on a webpage that would close the currently active tab in a browser without closing other tabs in the browser. When the user clicks the close link, an alert message should appear asking the user to confirm with two buttons, "YES" and "NO". If the user clicks "YES", close that page and If "NO", do nothing.
How can it be done? Any suggestions?
You will need Javascript to do this. Use window.close():
close();
Note: the current tab is implied. This is equivalent:
window.close();
or you can specify a different window.
So:
function close_window() {
if (confirm("Close Window?")) {
close();
}
}
with HTML:
close
or:
close
You return false here to prevent the default behavior for the event. Otherwise the browser will attempt to go to that URL (which it obviously isn't).
Now the options on the window.confirm() dialog box will be OK and Cancel (not Yes and No). If you really want Yes and No you'll need to create some kind of modal Javascript dialog box.
Note: there is browser-specific differences with the above. If you opened the window with Javascript (via window.open()) then you are allowed to close the window with javascript. Firefox disallows you from closing other windows. I believe IE will ask the user for confirmation. Other browsers may vary.
Try this
close
This method works in Chrome and IE:
<a href="blablabla" onclick="setTimeout(function(){var ww = window.open(window.location, '_self'); ww.close(); }, 1000);">
If you click on this the window will be closed after 1000ms
</a>
As far as I can tell, it no longer is possible in Chrome or FireFox. It may still be possible in IE (at least pre-Edge).
Sorry for necroposting this, but I recently implemented a locally hosted site that had needed the ability to close the current browser tab and found some interesting workarounds that are not well documented anywhere I could find, so took it on myself to do so.
Note: These workarounds were done with a locally hosted site in mind, and (with the exception of Edge) require the browser to be specifically configured, so would not be ideal for publicly hosted sites.
Context:
In the past, the jQuery script window.close() was able to close the current tab without a problem on most browsers. However, most modern browsers no longer support this script, potentially for security reasons.
Current Functionality:
window.close() will work on tabs opened by a script, or by an anchor with target="_blank" (opened in a new tab)
See #killstreet's comment on #calios's answer
Browser Specific work-arounds:
Google Chrome:
Chrome does not allow the window.close() script to be to be run and nothing happens if you try to use it. By using the Chrome plugin TamperMonkey however we can use the window.close() method if you include the // #grant window.close in the UserScript header of TamperMonkey.
For example, my script (which is triggered when a button with id = 'close_page' is clicked and if 'yes' is pressed on the browser popup) looks like:
// ==UserScript==
// #name Close Tab Script
// #namespace http://tampermonkey.net/
// #version 1.0
// #description Closes current tab when triggered
// #author Mackey Johnstone
// #match http://localhost/index.php
// #grant window.close
// #require http://code.jquery.com/jquery-3.4.1.min.js
// ==/UserScript==
(function() {
'use strict';
$("#close_page").click(function() {
var confirm_result = confirm("Are you sure you want to quit?");
if (confirm_result == true) {
window.close();
}
});
})();
Note: This solution can only close the tab if it is NOT the last tab open however. So effectively, it cannot close the tab if it would cause window to closes by being the last tab open.
Firefox:
Firefox has an advanced setting that you can enable to allow scripts to close windows, effectively enabling the window.close() method. To enable this setting go to about:config then search and find the dom.allow_scripts_to_close_windows preference and switch it from false to true.
This allows you to use the window.close() method directly in your jQuery file as you would any other script.
For example, this script works perfectly with the preference set to true:
<script>
$("#close_page").click(function() {
var confirm_result = confirm("Are you sure you want to quit?");
if (confirm_result == true) {
window.close();
}
});
</script>
This works much better than the Chrome workaround as it allows the user to close the current tab even if it is the only tab open, and doesn't require a third party plugin. The one downside however is that it also enables this script to be run by different websites (not just the one you are intending it to use on) so could potentially be a security hazard, although I cant imagine closing the current tab being particularly dangerous.
Edge:
Disappointingly Edge actually performed the best out of all 3 browsers I tried, and worked with the window.close() method without requiring any configuration. When the window.close() script is run, an additional popup alerts you that the page is trying to close the current tab and asks if you want to continue.
Edit:
This was on the old version of Edge not based on chromium. I have not tested it, but imagine it will act similarly to Chrome on chromium based versions
Final Note: The solutions for both Chrome and Firefox are workarounds for something that the browsers intentionally disabled, potentially for security reasons. They also both require the user to configure their browsers up to be compatible before hand, so would likely not be viable for sites intended for public use, but are ideal for locally hosted solutions like mine.
It is possible. I searched the whole net for this, but once when i took one of microsoft's survey, I finally got the answer.
try this:
window.top.close();
this will close the current tab for you.
The following works for me in Chrome 41:
function leave() {
var myWindow = window.open("", "_self");
myWindow.document.write("");
setTimeout (function() {myWindow.close();},1000);
}
I've tried several ideas for FF including opening an actual web-page, but nothing seems to work. As far as I understand, any browser will close a tab or window with xxx.close() if it was really opened by JS, but FF, at least, cannot be duped into closing a tab by opening new content inside that tab.
That makes sense when you think about it - a user may well not want JS closing a tab or window that has useful history.
Try this as well. Working for me on all three major browsers.
<!-- saved from url=(0014)about:internet -->
<a href="#" onclick="javascript:window.close();opener.window.focus();" >Close Window</a>
window.close() doesn't work in 2k21 because Scripts may close only the windows that were opened by them.
BUT if the tab is opened in the browser not manually, but automatically - then window.close() works.
Automatically (when close() works):
<a href="/close" target="_blank"> the browser will open address in the new tab and this tab can be closed with close()
when new browser tab is opened from another application (when you click a link in Telegram/Whatsup/Outlook etc) - OS will open new tab and it can be closed with close()
when you open the with window.open('ya.ru') - for sure it can be closed with close()
Manually (when it doesn't work):
when you open fresh browser and type in the address.
when you click (+) to open new tab and type in the address
Tested successfully in FF 18 and Chrome 24:
Insert in head:
<script>
function closeWindow() {
window.open('','_parent','');
window.close();
}
</script>
HTML:
Close Window
Credits go to Marcos J. Drake.
As for the people who are still visiting this page, you are only allowed to close a tab that is opened by a script OR by using the anchor tag of HTML with target _blank. Both those can be closed using the
<script>
window.close();
</script>
<button class="closeButton" style="cursor: pointer" onclick="window.close();">Close Window</button>
this did the work for me
a bit late but this is what i found out...
window.close() will only work (IE is an exception) if the window that you are trying to close() was opened by a script using window.open() method.
!(please see the comment of #killstreet below about anchor tag with target _blank)
TLDR: chrome & firefox allow to close them.
you will get console error:
Scripts may not close windows that were not opened by script.
as an error and nothing else.
you could add a unique parameter in the URL to know if the page was opened from a script (like time) - but its just a hack and not a native functionality and will fail in some cases.
i couldn't find any way to know if the page was opened from a open() or not,
and close will not throw and errors.
this will NOT print "test":
try{
window.close();
}
catch (e){
console.log("text");
}
you can read in MDN more about the close() function
It is guaranteed that the closing of tabs will not be tolerated in any future browsers. Using scripts like mentioned above will not work.
My solution was to use a Chrome Extension. A Chrome Extension can require tab manipulation permissions so it will be easy to handle the closing of any tab from the domain in which the extension's content script is active.
This is how the background script should look like:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log(sender)
console.log(message)
if(message.closeThis) {
closeTab(sender.tab.id)
}
});
const closeTab = id => {
console.log("Closing tab");
chrome.tabs.remove(id);
}
The content script should look like this:
window.addEventListener("message", (event) => {
// Only accept messages from ourselves
if (event.source !== window)
return;
if (event.data.type && (event.data.type === "APPLICATION/CLOSE")) {
console.log("Content script received APPLICATION/CLOSE event");
chrome.runtime.sendMessage({closeThis: true});
}
}, false);
Close the tab by calling this in your application (make sure the content scripts are enabled in your domain by specifying that in the manifest):
window.postMessage({ type: "APPLICATION/CLOSE" }, "*");
Be cautious when using this because Chrome Extensions' deployment can be a pain.
I just wanted to add that window.close() works in 2021, chrome 91, but not always. One of the cases when it works if there is no history in tab (you can't go back).
In my case I wanted to create self-destructing tab which closes after few seconds, but I was struggling with how to go to development server avoiding new tab, because apparently New tab is also tab and it is being saved in tab history :D I created link in about:blank tab with target=_blank attribute and it was leading to new tab where window.close() method finally worked!
This is one way of solving the same, declare a JavaScript function like this
<script>
function Exit() {
var x=confirm('Are You sure want to exit:');
if(x) window.close();
}
</script>
Add the following line to the HTML to call the function using a <button>
<button name='closeIt' onClick="Exit()" >Click to exit </Button>
You can try this solution to trick the browser to close the current window using JavaScript + HTML:
JS:
function closeWindow() {
if(window.confirm('Are you sure?')) {
window.alert('Closing window')
window.open('', '_self')
window.close()
}
else {
alert('Cancelled!')
}
}
HTML:
Some content
<button onclick='closeWindow()'>Close Current Window!</button>
More content
Due to strict browser behaviors, window.close() will only work if it's opened by window.open(...)
But I made a solution for this!
Add an empty hashtag with window.open(...) when it is NOT included
When the perfect time for closing occurs, call window.close
If 2. has returned an error, replace any hashtag or HTTP parameters with an empty hashtag and finally close the window
<button onclick="myFunction()">Close</button>
<script>
if (location.href.indexOf("#") == -1) {
window.open(location.href + "#", "_self")
}
function myFunction() {
try {
window.close()
} catch (err) {
window.open(location.href.substring(0, location.href.indexOf("?")).substring(0, location.href.indexOf("#")) + "#", "_self")
window.close()
}
}
</script>
Type close in this live demo
Here's how you would create such a link:
close
window.open("http://google.com", '_blank');
var childWindow = "http://google.com";
childWindow.location.href = "http://google.com";
I have an eventAddListener that loads http://google.com on a new tab with a button press, but right after it opens the new tab of google.com, I want it to REFRESH again. NOT my base page but the NEW tab page, by itself. The code I showed is just one of the examples out of 5 pages worth of google search which don't work.
UPDATE:
var win = window.open('google.com', 'New Window'); setTimeout(function () { var win = window.open('google.com', 'New Window'); },3000);
This is the best i could come up with. It opens new tab and "Reloads" the new tab rather than refresh it.
What I want is for example, you click on new tab, you paste a link then press enter, which EXECUTES the link. I basically want a javascript function which EXECUTES the link.
You can't do this.
In order to trigger a reload in the new tab/window you need to run JS in that tab/window.
The same origin policy prevents this.
If you had control over the new page then you could have an event listener running in it and post a message asking that listener to trigger a refresh.
Obviously you can't do that with Google's page.
This question, however, reads like an XY problem. If the goal is to display fresh (and not old, cached, out of date) information and the target page is not a third party one then you shouldn't be using JS to hack your way around caching. Instead set better caching rules on the target page in the first place.
I worked on something similar in the past few weeks and the code below worked for me.
index.html
<button onclick="openTab()">New Tab</button>
<script>
function openTab(){
//this opens a new tab while creating a variable name for that tab
var newTab = window.open("https://google.com","_blank");
//this refreshes that new tab
newTab.location.reload();
}
</script>
Just to prove that this works on the new tab I used the code
<script>
function openTab(){
//this opens a new tab while creating a variable name for that tab
var newTab = window.open("https://google.com","_blank");
//this will alert in the new tab
newTab.alert("New Tab");
//before the following reload code takes effect
//this refreshes that new tab
newTab.location.reload();
}
</script>
Hopefully that's what you are looking for.
From my understanding you want the new tab to refresh once opened with JavaScript instead of the current tab where you run the JavaScript code from.
That's not directly possible. The JavaScript code will only run for the tab it was executed in. The newly opened tab does not know that JavaScript code should be running. The current tab cannot pass over instructions for the new tab to execute.
However, you can select the newly opened tab manually first and then execute Javascript code to refresh the page. But that probably defeats the purpose of what you're trying to do.
I am using window.open in jquery to open a link in a new tab. Works fine for me in chrome/safari/firefox, but it does not work in IE10.
$('.div').click(function() {
$(this).target = "_blank";
window.open('http://url/15M');
return false;
});
How can I fix this?
The browser itself will decide when it's appropriate to open a new tab versus a new window, though you can influence its decision via browser settings. That being said, there are often times certain things we can do to encourage one way over the other. In this particular instance, I was able to get IE10 to open a window by passing along width and height values:
$("button").on("click", function () {
window.open("http://msdn.microsoft.com", "popup", "width=640,height=480");
});
Keep in mind that you ultimately have no control over whether something opens in a new tab, or a new window. That is entirely up to the user's machine; so don't bake any user experience dependencies into this assumption.
Try following:
$('.div').click(function() {
window.open('http://url/15M', '_blank');
return false;
});
I have a window I'm opening with a Javascript function:
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
}
I need it that once the new window opens that the focus returns to the original window.
How can I do that?
And where do I put the code - in the new window, or the old one?
Thanks!
This is known as a 'pop-under' (and is generally frowned upon... but I digress).. It should give you plenty to google about
You probably want to do something like:
var popup = window.open(...);
popup.blur();
window.focus();
Which should set the focus back to the original window (untested - pinched from google). Some browsers might block this technique.
After calling window.open, you may try to use
window.resizeTo(0,0);
window.moveTo(0,window.screen.availHeight+10);
this way can not really open window in background, but works in similar way. Chrome works fine, did not try other browser.
If Albert's solution doesn't work for you and you actually want the window visible, but to be opened behind the current window, you can try opening a new tab in the opener window and closing it right away, this will bring the focus back to the opener window.
window.open('link.html','','width=,height=,resizable=no');
window.open().close();
However, I believe whether the second window opens in a tab or a new window depends on your browser settings.
Please don't use "pop-unders" for evil.
You can use either
"blur" or
"focus" to do that required action.
"blur"
function newwindow()
{
var myChild= window.open('link.html','','width=,height=,resizable=no');
myChild.blur();
}
"focus"
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
window.focus();
}
Put the code in your parentWindow (i.e. the window in which you are now)
Both will work.
tl;dr - in 2022 - ctrl/cmd clicking on a button and window.open(url, "_blank") in a javascript button handler's for loop will open multiple tabs in the background in Chrome.
I'm looking for this as of 2022 and none of the answers here worked (here and everywhere else I looked). My use case is clicking a button in a (progressive) web app which opens deep links to items in a list in background tabs (i.e. not "for evil").
It never occurred to me that ctrl/cmd + clicking on the button would open tabs in the background, but it does just as if the user clicked on an anchor tag itself directly - but only in Chrome. Combined with Chrome's relatively recent tab grouping feature, this can be very useful inside PWAs.
const isMozilla =
window?.navigator?.userAgent?.toString().toLowerCase().includes('firefox') ?? false;
for (let index = 0; index < urls.length; index++) {
const url = isMozilla ? urls.reverse()[index] : urls[index];
window.open(url, "_blank");
}
Note: I reverse() the array on Mozilla to get the order of newly created tabs as the user would expect them.
You can just use '_self'. It will be stay to the same page an
window.open(url, '_self');
i have Problem with opening popups in javascript i have this function to open my popups in IE6 and IE7:
function open_window(Location,w,h) //opens new window
{
var win = "width="+w+",height="+h+",menubar=no,location=no,resizable,scrollbars,top=500,left=500";
alert(win) ;
window.open(Location,'newWin',win).focus();
}
it's working . i mean my new window opens but an error occurs. The Error Message is :
'window.open(...)' is null is not an object.
do you want to countinue running script on this page ?
then i have button in onclick event it's will call a function to close current window an refresh the opener function is
function refreshParent(location)
{
window.opener.location.href = location ;
window.close();
}
it's also gives me error : window.opener.location is null or not an object but i'm sure i'm passing correct parameters
i call it like this :
for second part :
<input type="button" name="pay" value="test" onclick="refreshParent('index.php?module=payment&task=default')" >
for first part :
<a onclick="javascript:open_window('?module=cart&task=add&id=<?=$res[xproductid]?>&popup=on','500' , '500')" style="cursor:pointer" id="addtocard"> <img src="../images/new_theme/buy_book.gif" width="123" border="0"/> </a>
it's really confuse me . Please Help ;)
When popup windows opened using window.open are blocked by a popup blocker, a feature of pretty much any modern browser these days, the return value of window.open() is not a window object, but null.
In order to circumvent these issues you would need to test the value returned by window.open() before attempting to invoke any methods on it.
Below is a piece of code to demonstrate how to go around this problem:
function open_window(Location,w,h) //opens new window
{
var options = "width=" + w + ",height=" + h;
options += ",menubar=no,location=no,resizable,scrollbars,top=500,left=500";
var newwin = window.open(Location,'newWin',options);
if (newwin == null)
{
// The popup got blocked, notify the user
return false;
}
newwin.focus();
}
In general, popup windows should be used only as a last resort or in controlled environments (internal company website, etc). Popup blockers tend to behave in very inconsistent ways and there may be more than a single popup blocker installed in a given browser so instructing the user on how to allow popups for a given website is not necessarily a solution. Example: IE7 + Google toolbar = two popup blockers.
If I may suggest, perhaps you should consider using something like this:
http://jqueryui.com/demos/dialog/
The advantages are numerous:
Skinnable, so you can create a more consistent look to match your website.
No popup blockers.
Good API and documentation that is consistent across most, if not all, major browsers.
If you still require that the newly opened "window" contain an external URL, you could use an IFRAME inside the opened dialog window.
Hope this helps,
Lior.
Works perfectly fine for me. Tested in IE6/7/8.
Of course I couldn't test it with your URLs so I replaced these with simple filenames. I'd suggest you try it also with simple filenames and see if it also fails then.
Beside that...
You don't need to add "javascript:" at the beginning of onclick attribute value.
It would also be good if you added a href="..." attribute to the link with the same URL that you give to open_window. Then it would become a real link and you wouldn't have to add cursor:pointer to it. For example:
<a href="?module=cart&task=add&id=<?=$res[xproductid]?>&popup=on"
onclick="open_window(this.href, '500' , '500'); return false;"> ...
Here is a way to have your cake and eat it too
I have not tested it on all browsers but it should really work
function open_window(url,target,w,h) { //opens new window
var parms = "width="+w+",height="+h+",menubar=no,location=no,resizable,scrollbars,top=500,left=500";
var win = window.open(url,target,parms);
if (win) {
win.focus();
return false; // cancel the onClick
}
return true; // make the link perform as normal
}
Using the link
<a href="?module=cart&task=add&id=<?=$res[xproductid]?>&popup=on"
target="newWin"
onclick="return open_window(this.href,this.target,500,500)"
id="addtocard"><img src="../images/new_theme/buy_book.gif" width="123" border="0"/></a>
which even saves you the silly cursor thing since it is an actual link which works even when JS is turned off