I have a dotnet application in which I have to close the current window and then open the new window again in runtime. I have used Javascript for it. The code is as follows:
function OpenNewWindow() {
if (ConfirmStartTest()) {
closeWindow();
window.open("OnlineTestFrame.aspx", "_Parent", "model=yes,dailog=no,top=0,height=screen.height,width=screen.width,status=no,toolbar=no,menubar=no,location=no,zoominherit =0,resizable =no,scrollbars=yes,dependent=no,directories=no,taskbar=no,fullscreen=yes");
self.focus();
}
}
//taking the confirmation for starting test
function ConfirmStartTest() {
var result = confirm("Do you want to start the test now?");
return result;
}
//function to close the current window
function closeWindow() {
//var browserName = navigator.appName;
//var browserVer = parseInt(navigator.appVersion);
var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
if (ie7)
{
//This method is required to close a window without any prompt for IE7
window.open('','_parent','');
window.close();
}
else
{
//This method is required to close a window without any prompt for IE6
this.focus();
self.opener = this;
self.close();
}
}
Now, when I am running this application in IE7 and IE6, it is not running. But, in IE8 it is running fine.
This code was working fine for all IE6 n IE7 previously. All of a sudden it is giving error.Its not able to open the new window and stopping abruptly in b/w.
If anyonw has any idea regarding this, please let me know.
This is due to the assignment of self.opener.
12/04 Microsoft started pushing out Security Bulletin MS11-018 via Windows Update which closed of several vulnerabilities related to memory - one of these affected the opener property which no longer can be assigned to.
Nothing like closing a window and expecting anything after it to want to run.
Flow of the code
Function called
Close Window
Open window <-- How can I run if parent is closed?
Focus window
[rant]
What you are trying to do here by forcing a user to use your own pop up window so it has no chrome is very bad user experience. You are deleting a users history. Leave my browser alone! There is a reason why you have to do hacky stuff to close a window, the browsers do not allow you to do it.
[/rant]
Related
I'm trying to create a script which will run when any browser console is opened or closed. Is there any way to detect if the browser console in all browsers (Firefox/IE/Chrome/Safari/Opera) is open or not via JavaScript, jQuery, or any other client-side script?
If you are willing to accept an interference for the user,
you could use the debugger statement, as it is available in all major browsers.
Side note: If the users of your app are interested in console usage, they're probably familiar with dev tools, and will not be surprised by it showing up.
In short, the statement is acting as a breakpoint, and will affect the UI only if the browser's development tools is on.
Here's an example test:
<body>
<p>Devtools is <span id='test'>off</span></p>
<script>
var minimalUserResponseInMiliseconds = 100;
var before = new Date().getTime();
debugger;
var after = new Date().getTime();
if (after - before > minimalUserResponseInMiliseconds) { // user had to resume the script manually via opened dev tools
document.getElementById('test').innerHTML = 'on';
}
</script>
</body>
devtools-detect should do the job. Try the simple demo page.
devtools-detect → detect whether DevTools is open, and its orientation.
Supported Browsers:
DevTools in Chrome, Safari, Firefox & Opera
Caveats:
Doesn't work if DevTools is undocked (separate window), and may show a false positive if you toggle any kind of sidebar.
I don't think it is directly possible in JS for security reasons.But in here
they are claiming that it is possible and is useful for when you want something special to happen when DevTools is open. Like pausing canvas, adding style debug info, etc.
But As #James Hill tell in this, I also thinks even if a browser chose to make this information accessible to the client, it would not be a standard implementation (supported across multiple browsers).
Also can also try this one also here.
It's not possible in any official cross browser way, but if the occasional false positive is acceptable, you can check for a window.onresize event. Users resizing their windows after loading a page is somewhat uncommon. It's even more effective if you expect users will be frequently opening the console, meaning less false positives as a percentage.
window.onresize = function(){
if ((window.outerHeight - window.innerHeight) > 100) {
// console was opened (or screen was resized)
}
}
Credit to https://stackoverflow.com/a/7809413/3774582. Although that question is chrome specific, the concept applies here.
To expand on this, if you need a very low tolerance on false positives, most window resizes will trigger this event dozens of times because it is usually done as a drag action, while opening the console will only trigger this once. If you can detect this, the approach will become even more accurate.
Note: This will fail to detect if the console is already open when the user visits the page, or if the user opens the console in a new window.
(function() {
'use strict';
const el = new Image();
let consoleIsOpen = false;
let consoleOpened = false;
Object.defineProperty(el, 'id', {
get: () => {
consoleIsOpen = true;
}
});
const verify = () => {
console.dir(el);
if (consoleIsOpen === false && consoleOpened === true) {
// console closed
window.dispatchEvent(new Event('devtools-opened'));
consoleOpened = false;
} else if (consoleIsOpen === true && consoleOpened === false) {
// console opened
window.dispatchEvent(new Event('devtools-closed'));
consoleOpened = true;
}
consoleIsOpen = false;
setTimeout(verify, 1000);
}
verify();
})();
window.addEventListener('devtools-opened', ()=>{console.log('opened')});
window.addEventListener('devtools-closed', ()=>{console.log('closed')});
Here is a code that worked for me.
This solution works like a charm
https://github.com/sindresorhus/devtools-detect
if you are not using modules - disable lines
// if (typeof module !== 'undefined' && module.exports) {
// module.exports = devtools;
// } else {
window.devtools = devtools;
// }
and result is then here
window.devtools.isOpen
I for my project use the blur event.
function yourFunction() {}
window.addEventListener('blur',(e)=>{e.preventDefault(); yourFunction()})
This will execute yourFunction when the window loses focus.
For instance when someone opens the DevTools.
Okay seems like it also fires when you try to access a different window... so maybe not the best solution.
Maybe pair it with looking at the width of the browser.
If it chainged you can be pretty sure about it I think
I have been trying to figure this one out for a while, but when I try to reference a window that I opened the handle is always undefined.
It is worth noting that this is being used in a userscript and here is the snippet in question:
var donateWindow;
// ######################################################################
// # Show the donation popup and open a window to paypal site
// ######################################################################
function showDonateWindow()
{
if (window.confirm("Question here"))
{
if (! (typeof(donateWindow) == 'undefined' || donateWindow.closed)) window.donateWindow.close();
window.donateWindow = window.open("http://somesite.com/","tabName");
}
}
Any help on this would be very appreciated. It would seem no matter what I do window.open returns the value "undefined".
My goal is to have a popup shown, but if one is already open it should just replaced the old one. This works as expected in FF, but for the life of me I can not get it going in Chrome.
Why are you trying to close existing window before open a new one? you don't need to do that.
if you just use the same name for window when you open it, it will replace the existing one if there is.
this means you don't need to look for if there is an opened window.
function showDonateWindow()
{
if (window.confirm("Question here"))
{
window.open("http://somesite.com/","donateWindowName");
}
}
I have some JScript code (converted from some old VBScript) that starts like this:
var Word = new ActiveXObject("Word.Basic");
Word.FileNew(); // opens new Word document
Word.Insert(IncorrectText);
Word.ToolsSpelling(); // opens spell check behind IE
The idea is to utilize the MS Word spell check for browser use, and it works well in XP, but the spell check box opens in the background in Windows 7 / IE 8 (this question tells me that the problem started in Vista and is probably an OS issue, not a browser or Office issue).
So my question is, how can I bring this window to the foreground? One important note is that the last line, Word.ToolsSpelling();, locks up my script, so anything I do will need to be before that.
I've tried
var wshShell = new ActiveXObject("WScript.Shell");
wshShell.AppActivate("Document1 - Microsoft Word"); // or some other text
before the ToolsSpelling call, but this does not do anything (maybe because the Word document is not actually revealed at this point?). Of course, this will only work if no "Document1" is already opened, so this is a questionable thought to begin with.
Per this answer, I tried using window.blur(); in order to blur IE, but this will only work if the IE window is the only one opened. Maybe there's some way I can loop through all opened windows and apply this?
SetForegroundWindow looked promising, but I don't know how to use it in JSript.
Any ideas?
Note: Browser permissions will be completely open for this site.
Update: Turns out if you use Word.Application, the spell check comes up in front as it should. Only the Word.Basic method has this problem (I don't expect to know why this side of eternity):
var wordApp = new ActiveXObject("Word.Application");
wordApp.Documents.Add();
wordDoc = wordApp.ActiveDocument;
... // safety checks before insertion
wordSelection.TypeText(IncorrectText);
wordDoc.CheckSpelling();
wordApp.Visible = false; // CheckSpelling makes the document visible
You might be able to jigger the window state. When the window is maximized after having been minimized, Windows will stack that in front (zIndex to top).
Something like:
var WIN_MAX = 2;
var WIN_MIN = 1;
var Word = new ActiveXObject("Word.Application");
Word.Visible = true;
// minimize the app
Word.WindowState = WIN_MIN ;
// in 500ms, maximize
setTimeout(function () {
Word.WindowState = WIN_MAX;
}, 500);
The setTimeout call seeks to work around a timing issue; Windows will sometimes "get confused" when a programmatic minimize/maximize happens in immediate succession. You might have to extend that delay a little, test it repeatedly and see what kind of results you get.
I'm creating a popup window and attaching a callback function to it. There is a button in the popup's page which calls this callback when clicked. This works in Firefox 4 and Chrome 10, but not IE 9. The "myPopupCallback" property that I add to the window is found and executed by Firefox and Chrome. In IE, it is undefined.
Is there something about IE that causes problems with attaching data or functions to a window?
Main window code
var popup = window.open(url, '', 'status=0,menubar=0,toolbar=0,resizable=1,scrollbars=1');
$(popup.document).ready(function()
{
popup.myPopupCallback = function(rows)
{
// ...do stuff with rows...
};
});
Popup window code
$('#btn-ok').click(
function()
{
var rows = $('#rows');
// IE 9 throws an error on the next line because window.myPopupCallback is undefined
window.myPopupCallback(rows);
});
window.open() is a non-blocking operation which means that before the new window has finished opening JavaScript will move on to next line of code. Because of this, setting a property may not "stick" if it's done too soon. I just ran into this problem myself.
Thanks to a lot of help from Erik I found the following seems to work pretty well.
var popup = window.open(
url, '', 'status=0,menubar=0,toolbar=0,resizable=1,scrollbars=1'
);
$(popup.document).ready(function(){
var setPopupPropertiesInterval = setInterval(
function setPopupProperties() {
popup.myPopupCallback = function(rows)
{
// ...do stuff with rows...
};
if (popup.closed || popup.myPopupCallback) {
clearInterval(setPopupPropertiesInterval);
}
}, 1
);
});
This will keep trying to add the function to the popup window until it is added or the popup window is closed.
In my extremely brief testing this worked across browsers but I'm not sure about the performance implications of such a fast interval and had no issues with performance. Note that most (all?) browsers will not actually run the code in 1 ms intervals, but something a bit higher, usually 10 ms. Chrome is an exception to this in that it tries to get close to 1 or 2ms.
On one Windows XP machine running IE 7 I ran into an issue where the browser would freeze upon launching the pop-up. The window would pop-up but nothing would load and the browser would become slow to respond. However, I have tested this on several other machines running Windows XP and IE 7 and was not able to reproduce the issue.
I'm trying to do something like this
win = null;
win = window.open('/url/to/link','tab');
win.focus();
but in IE7 it returns me at the line of win.focus(); the error that win is null.
How can I solve it?
Thanks in advance!
You can try adding a slight delay to make sure that the window is open
//win = null; <--useless
win = window.open('/url/to/link','tab');
if(win)window.focus();
else{
var timer = window.setTimeout( function(){ if(win)win.focus(); }, 100 );
}
This day in age, most people avoid pop up windows and use modal layers.
Blockquote <
Return Value
Returns a reference to the new window object. Use this reference to access properties and methods on the new window.
Internet Explorer 7 on Windows Vista: Opening a new window from an application (other than the Internet Explorer process) may result in a null return value. This restriction occurs because Internet Explorer runs in protected mode by default. One facet of protected mode prevents applications from having privileged access to Internet Explorer when that access spans process boundaries. Opening a new window by using this method generates a new process. For more information about protected mode, see Understanding and Working in Protected Mode Internet Explorer. This commonly occurs for applications that host the WebBrowser control.>
Window.Open method documentation
When you launch a popup, give it a variable name:
myWin = window.open(etc)
//in the child window, call window.opener.myFocusFunction()
//in the parent window, use this...
function myFocusFunction(){
myWin.focus();
//myWin.blur();
//uncomment as needed!
}
Have a play, it works for me.