JS showModalDialog not working in chrome as modal - javascript

I am using showModalDialog() in my application, for user to view articles from different sources as modal popup.
It work fine with FF and IE, but in chrome it's not behaving as modal, I can still go on parent window and click on any element in it.
I wanted to make it work same as IE and FF.
I have looked at few work-around
1) set onfocus event on parent window, and focus child again on it.
<script type="text/javascript">
setInterval(checkFocus, 10);
var mywindow;
function openModal() {
var a = new Array;
a[0] = 1;
a[1] = 4;
mywindow = window.showModalDialog(myurl,
a, "dialogwidth: 1000; dialogheight: 700; resizable: yes;center : yes;");
}
function checkFocus() {
if (mywindow != null && mywindow != undefined) {
if (window.focus) {
mywindow.focus();
}
}
}
</script>
but this is not seems to work as expected.
2) set onblur event on child window, to focus itself again
this solution i have read from some online sources. i can apply this solution if only child window is customized page from on my domain only , but as my child window can be any url from any domain It is not applicable in my case.
I need to make it work , can anybody suggest me on this??

Chrome has serious bugs with its implementation. Most importantly the window Chrome displays isn’t modal (see Chromium bug #16045), meaning, the user is able to interact with the original window before dealing with the modal dialog.

Related

using modernizr to determine if multiple window open is supported

the problem I've encountered is documented here.
window.open behaviour in chrome tabs/windows
where you can not open multiple windows via javascript in chrome.
I would like to open the multiple windows if it is supported, if it is not supported I will simply return a list of links.
is there a way using modernizr or something besides browser sniffing that I can determine if the behavior is supported?
This ability to open multiple windows various widely between browser and even by browser config.
So never assume you will be able to open multiple pop ups, you might be able to, but you can only know by testing, it's very easy to test tough.
To test if opening a pop up succeeded, inspect the return value.
var popupWindow = window.open('http://www.google.com/');
if (!popupWindow) {
console.log('the window did not open');
// do other stuff
}
If the window opened the return value will be a Window object.
If the the window did not open, the return value will be be falsy, this exact return value can vary from pop up blocker to pop up blocker, but generally you can assume the value to be falsy if the window did not open; meaning undefined or null.
As such it's very easy to trigger an alternate method in case the window failed to open.
You do not need modernizr or any plugins for this, this behavior of returning the Window object is the same in all browsers.
MDN reference:
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
Firefox and Safari seem to support opening multiple windows by default. Chrome however will block the second window and show the little "pop up" blocked message.
Additionally Chrome will also block opening windows that did not originate from direct users actions; meaning a click or a key press.
Nothing like modernizr or any custom code is going to give you any type of feature detection. The main reason is because all major browsers require some sort of user action to open a new window programmatically - usually a click. So creating a feature detection is out of the question.
This is an interesting question and one where thinking in terms of "progressive enhancement" might help you get to a good solution.
First, let's assume that you cannot open multiple windows in any browser. What would you do? Show a list of links as you've suggested. By adding something like target="_blank" to each link, now we have a working app without any JavaScript (or if the user has JavaScript disabled):
<section id="links-wrap">
<a href="/page-A.html" target="_blank" />
<a href="/page-B.html" target="_blank" />
</section>
This baseline of functionality will work on every single browser ever made - your Treo visitors will love you. However, this experience is less than ideal because the links are likely to open new tabs instead of new windows. So let's use JavaScript to open a new window whenever a link is clicked. Lets also hide each link after it is clicked and position each window so that they are not overlapping:
function openWindowFromLink (link, idx) {
var top = idx % 2 * 600;
var left = Math.floor(idx/2) * 600;
var win = window.open(link.href, 'Window '+ top +'x'+ left, 'width=600,height=600,top='+ top +',left='+ left);
if (win) {
link.style.display = "none";
}
return win;
}
function handleLinkClick(ev) {
ev.preventDefault();
var link = ev.target;
var idx = 0;
var prev = link.previousSibling;
while (prev) {
if (prev.nodeType === 1) {
idx++;
}
prev = prev.previousSibling;
}
openWindowFromLink(link, idx);
}
document.getElementById('links-wrap').addEventListener('click', handleLinkClick);
Now comes the hard part: how can we open many windows at once. As we know, Chrome will only allow one window to open per user click. While other browsers might not have this same restriction, they may add it in the future (I'm actually surprised that they don't all have this restriction right now). So lets assume that all browsers have the same limitation as Chrome. Users don't want to click every single link every time - so lets give them a click target that they can click really fast to open all of the windows. Creative wording will reduce the annoyance of this task.
<div id="rapid-click-box">
Click me really fast and see what happens!
</div>
... and some JavaScript:
var clickBox = document.getElementById('rapid-click-box');
var clickCount = 0;
clickBox.addEventListener('click', function handleRapidClick (ev) {
var link = links[clickCount];
if (link.style.display !== 'none') {
openWindowFromLink(link, clickCount);
}
if (++clickCount === links.length) {
clickBox.removeEventListener('click', handleRapidClick);
clickBox.style.display = 'none';
}
});
Finally, lets take care of those browser which allow multiple windows to be opened at once. We still need the user to click in order to call window.open - so lets get creative and see how we can make the user click something. A cleverly worded welcome message should suffice:
<div id="welcome-message" style="display:none">
<h1>Hey, welcome to my site. Are you a human?</h1>
<button>Yes</button>
</div>
<script>
// show the welcome message immediately if JS is enabled
document.getElementById('welcome-message').style.display = 'block';
</script>
... and once again, a little bit of JavaScript:
var button = document.getElementsByTagName('button')[0];
button.addEventListener('click', function handleYesClick (ev) {
ev.preventDefault();
button.removeEventListener('click', handleYesClick);
document.getElementById('welcome-message').style.display = 'none';
for (var i = 0, l = links.length; i < l; i++) {
if ( !openWindowFromLink(links[i], i) ) {
break;
}
}
if (i === links.length) {
clickBox.style.display = 'none';
}
});
And a fiddle to show it all in action:
https://jsfiddle.net/q8x5pqsw/

IE Context Menu Item In Javascript

I am trying to create an IE Context Menu Item that points to a Javascript html file as described here https://msdn.microsoft.com/en-us/library/bb735853(v=vs.85).aspx#IEAddOnsMenus_topic1
under the "Adding to a context menu" section. I have the Context menu entry listed in HKCU\Software\Microsoft\Internet Explorer\MenuExt
and it points to an html file with javascript in it. Here is the Javascript code I am using.
<script language="JavaScript">
function pausescript(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
{
var win = window.open("http://www.example.com");
pausescript(2000);
win.close();
}
</script>
I am trying to pop up a window to the url then wait 2 seconds and close the window. It is working but when it closes the pop up window for some reason IE loses focus and any other window besides IE regains focus even though I am forcing the pop up from an IE context menu. How do I make IE get the focus after the pop up window closes?
Your problem is how to set the registry. I use windows 8.1 and I set the registry in this way:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt\&Live Search]
#="C:\Usr\StackOverflow\livesearch.htm"
"Contexts"=dword:00000001
All worked fine (your script).
Like you can see the value of Contexts is different from the one described in the guide (instead of 0x10 i used 1).
It's unusefull to say you need to restart the browser.
The FOCUS PROBLEM
After closing the window poup window IE loses the focus.
Like described in MSDN you need to access external.menuArguments property to get the window handler of current ie.
So the javascript code is:
<script language="JavaScript">
function pausescript(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
{
var win = window.open("http://www.example.com");
pausescript(2000);
win.close();
try {
// access the current browser window
var parentwin = external.menuArguments;
// get the document element
var doc = parentwin.document;
// focus it
doc.body.focus();
} catch(ex) {
alert(ex);
}
}
</script>

Window.open issue in firefox and IE

I am opening a new window on clicking a hyper link.
Issue:
After minimizing the window, again if I click on hyper link, the same window should be opened(In chrome minimized window will open up). But this is not happening in firefox and IE. Can anyone please help.
<html>
<head></head>
<body>
<p>Visit our HTML tutorial</p>
</body>
</html>
window.open allows you to specify a unique identifier to your popup; this allows you to open many links always in the same popup window.
If you use different identifiers on different links, it should open multiple popup windows.
<p>
Visit our HTML tutorial
</p>
<p>
Visit our HTML tutorial
</p>
If the strWindowFeatures parameter is used and no size features are defined, then the new window dimensions will be the same as the dimensions of the most recently rendered window.
you might want to check this link
window.open web api for mozilla
The idea of Unique ID in the parameter's list simply doesn't work as suggested in another answer.
You need a function for to do what you need in IE and FF. The trick is to get a function to see if it has opened a window before and do nothing if it has.
<script>
var opened = false;
function openWindow(){
if (!opened) {
w = window.open('', 'test', 'width=1500, height=900');
w.location = "http://www.google.com";;
w.onload = function() {
w.onunload = function() {
opened = false;
};
};
opened = true;
}
}
</script>
I'm using the opened global variable to track this. We set the newly created window to set false to this variable when it closes. Now the function can decide if it should really open a new window. Please note the following points:
We use onLoad function of the new window to set onUnload. Because IE seems to replace whatever the event handlers set here soon after it loads the page.
You can see that we first open a blank window and then set the url of it. This is because IE returns nothing when opening a new window if it is from another domain.

window.opener alternatives

I am opening a modal popup window. Then I access a parent window textbox and other attributes using window.opener. It is working fine in firefox but not in IE8. It gives error 'window.opener is null'. How can I access parent window attributes in child window which works in both browsers.
There are two ways to solve the problem:
Note: "window.opener" is not supported by IE if "showModalDialog" is been used.
1) Instead of "window.showModalDialog" use "window.open"
2) If you want to use "window.showModalDialog" then do the following:
<script language="javascript" type="text/javascript">
function YourFunction()
{
var opener = null;
if (window.dialogArguments) // Internet Explorer supports window.dialogArguments
{
opener = window.dialogArguments;
}
else // Firefox, Safari, Google Chrome and Opera supports window.opener
{
if (window.opener)
{
opener = window.opener;
}
}
// write you code and refer "opener"
window.close();
}
</script>
You can pass arguments to showModalDialog function. Simply pass window object as an argument.
window.showModalDialog(theURL, window);
Yo can access the arguments from the modal window using dialogArguments. See: http://msdn.microsoft.com/en-us/library/ms533723%28VS.85%29.aspx
var openerWindow = window.dialogArguments;
Disable Internet Explorer's "Protected Mode", which prevents access to this object.
The steps for this are:
Press Alt+T to show the Tools menu
Click "Internet options"
Select the "Security" tab
Make sure zone selected contains your site. For an intranet site it would typically be "Local intranet" zone.
Untick "Enable Protected Mode"
Close all IE tabs and windows and re-open.
Now you should be able to access the window.opener object.
The approach I would take is the following:
Use an existing JavaScript UI library because you are not the first person to ever want to do this, failing that
Create a function called OpenWindow, that browser sniffs for the window.opener method
For example:
if(window.opener == undefined) {
//probably not Firefox...
}
and if it finds it then uses it, else it tests for the IE variant and uses it. And then it checks Safari's version, etc...
As a cross-browser alternative, you can give a custom attribute to the new window while you are opening it:
var popup = window.open(...);
popup.isPopup = true;
Then, in the referred page:
if (window.isPopup) {
// Do something
}
else {
// Not in a popup
}

I need to open a new window in the background with JavaScript, and make sure the original is still focused

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');

Categories