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.
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 got a chrome extension and in the event of a new tab I want to get the window handle in windows if the current window.
On the event I got the tab object and I got chrome's internal window id but this is not the handle in windows.
chrome.tabs.onCreated.addListener(
function (tab)
{
var intMainWindowHwnd = 0; // how to get it? not tab.windowId…
});
Thanks!
Well, if anyone encounter the same problem, i solved it using a NPAPI Plugin in C++ that get access to win32api...
In Invoke method i've checked for my method (GetProcessId) and got the parent process (since the addon is in a different process):
ULONG_PTR MyAddon::GetParentProcessId() // By Napalm # NetCore2K
{
ULONG_PTR pbi[6];
ULONG ulSize = 0;
LONG (WINAPI *NtQueryInformationProcess)(HANDLE ProcessHandle, ULONG ProcessInformationClass,
PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength);
*(FARPROC *)&NtQueryInformationProcess =
GetProcAddress(LoadLibraryA("NTDLL.DLL"), "NtQueryInformationProcess");
if(NtQueryInformationProcess){
if(NtQueryInformationProcess(GetCurrentProcess(), 0,
&pbi, sizeof(pbi), &ulSize) >= 0 && ulSize == sizeof(pbi))
return pbi[5];
}
return (ULONG_PTR)-1;
}
Then i got the main hwnd of this process and return it to my js addon.
I am building an extension in Firefox and I wonder if there is a way to know when opening a browser how many instances are open using javascript?
For example I open one instance of Firefox browser I want to get the number of the current instances.
Any ideas?
Found something that may help you:
nsIWindowMediator is a component that keeps track of open windows. It has getEnumerator method that allows you to get all open windows.
If you loop through it, and count them, you get the number of open windows, like so:
var windowMediator = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var enumerator = windowMediator.getEnumerator(null);
var count = 0;
while (enumerator.hasMoreElements()) {
var myWindow = enumerator.getNext();
count++;
}
alert(count);
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]
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.