- JavaScript window.open returns null sometimes
- Windows open return null
- Question
- All replies
- On IE9, Win 7 window.open() returns null instead of reference of the opened window
- 4 Answers 4
- window.open from add-in in Windows Outlook using WebView1 returns null window #1525
- Comments
- westconference commented Nov 26, 2020 •
- Expected Behavior
- Current Behavior
- Steps to Reproduce, or Live Example
- Context
- Your Environment
- Форум
- Справочник
- window.open
- Синтаксис
- Аргументы
- Описание, примеры
- Связь между окнами
- Строка параметров
- Основные кроссбраузерные параметры
JavaScript window.open returns null sometimes
I am attempting maintenance on a system I did not write (and aren’t we all?). It is written in C Sharp and JavaScript, with Telerik reports.
It has the following code included in JavaScript that runs when the user clicks a button to display a report in a separate window:
Then the load function:
When I execute this (in Chrome, at least), it does pop up the window and put the report in it. However, breakpoints in the c# code indicate that it is getting called 2 or 3 times. Breakpoints in the JavaScript and examination of the little log in the JavaScript debugging environment in Chrome show that the call to win.focus() fails once or twice before succeeding. It returns an undefined value, and then it appears that the first routine above is executed again.
I am inclined to think it some kind of timing issue, except that the window.open() call is supposed to be synchronous as far as I can tell, and I don’t know why it would succeed sometimes and not others. There is a routine that gets executed on load of the window, perhaps that’s somehow screwing up the return of the value from open().
I am not a JavaScript person much, as those of you that are can likely tell by this time. If there is something with the code I’ve put here that you can tell me is incorrect, that’s great; what I’m more hopeful for is someone who can explain how the popup-report-in-frame is supposed to work. Hopefully I can do it without having to replace too much of the code I’ve got, as it is brittle and was not, shall we say, written with refactoring in mind.
Windows open return null
Question
I have encountered a bug in the Edge browser’s Javascript implementation of window.open(). When the ‘open’ function is called, there should be an object returned that is the newly opened window, but returns null.
The window opens, but the whole screen, and the window.opener parameter in it is null.
You can check here:
Do you have any information about this bug, and when or if a fix for it might be available?
All replies
Sam Hobbs
SimpleSamples.Info
Problem Description:
I’m trying to open a popup window for authorization users via google oauth.
Google oauth call redirect in opened popup window with auth code, that we need to pass to parent window.
To do this I need to call window.opener’s function from that popup.
In all browsers it works fine, but Edge. In Edge window opens on full screen and window.opener parameter in it is null.
Steps to Reproduce:
Code:
1. Run Microsoft Edge
2. Go to https://littlebigsnake.com
3. Open console
4. enter window.open(«https://accounts.google.com/o/oauth2/auth», «new», «width=800,height=600,resizable=yes,toolbar=no,location=no,menubar=no,status=no,directories»);
UI Example:
1. Run Microsoft Edge
2. Go to https://littlebigsnake.com
3. Push play
4. Press google oauth button
Actual Result:
Edge opens new fullscreen window without any information about opener ( window.opener == null )
Expected Result:
Edge opens popup window with 800x600px size and window.opener parameter != null.
Any Workarounds:
1. Use other browsers
2. Open blank page
or relative page
something appears to BLOCKING your popup window when you run it on Edge. I disable flash in Edge and use the Adblock + extension.
You should test by running Edge in InPrivate mode to see if one of your extensions or the built-in popup blocker is blocking your popup window.
a common design pattern is to use just window.open([url]) (viz: no size or position constraints)
Credential validation services like FB connect or Google should be opened in a new window/tab without position or size arguments.
Replace the scripted window with just an action link.. login with google
Your site has no feature detection for IE ActiveX filtering or Flash blocking extensions. Flash (if supported) is pre-installed on modern devices. the adobe getflash url will only confuse visitors.
We’re observing the same issue on our end. The popup is not being blocked by the browser: it is displayed, not respecting the windowFeatures given, and the call to window.open returns null which does not respect the specs:
«If the window couldn’t be opened, the returned value is instead null»
Here, the popup is actually opened. I think this only happens on Edge 15+. I noticed that when the main page is `http:` and it opens a popup to `https:`, it could create such issue. But we’re also observing it when both origins are https:.
Let me know if you need any other info, it’s a pretty big issue.
(My account is not verified so I couldn’t provide links to MDN Web Docs with the specs)
try running edge in InPrivate mode, so no extensions (form fillers) or site cookies are involved. Its normal for window.open IN EDGE to ignore some legacy size and position features and UI features. I imagine that the google apis allow you to specify the size of the popup in their api settings.
the common design pattern(for all web browsers, desktop and mobile) (for credential verification api’s like FBConnect and google plus) is to use window.open(url). viz without any ‘features’. that is open the credential verification domain in its own window, without any size or position constraints. Both the domains of the parent window and the credential verification service must support and use https.
this forum is for IE web development questions. there is an Edge developer forum at stackoverflow.com. there is also the developers.google.com forums.
Without a reproduction url, its impossible for a confident guess at an answer.
On IE9, Win 7 window.open() returns null instead of reference of the opened window
I am trying something like below,
All browsers return the window ref for window.open(), but IE 9 returns NULL. Does anybody have more information on why null is returned or possibly a workaround solution for IE9?
4 Answers 4
window.open returns a NULL reference object if Enable Protected Mode is checked under Internet Options->Security->Security Level for this zone and the ZONE is different i.e. in my case local file opening a popup from Intranet.
window.open returns a reference object even if Enable Protected Mode is checked when mysite.com opens someothersite.com in popup window i.e. Internet->Internet
Out of curiosity, what’s your windowId ? Does it have a space in it?
Actually in my case, I was getting window.open reference null if I’m opening localhost or intranet site URL. If my popup contains any internet site url then I’m getting window object in reference. I did following to resolve this:
- Open IE > Tools > Internet Options
- Go to Security Tab
- Enable Protected Mode by clicking the checkbox
- Restart IE
Now, it started giving me window object reference for popup window opened with Intranet Sites.
Also, it could be the URL problem where it is secure or added in trusted sites zone. If you can provide the URL it will help.
Hope this helps.
We had this problem with our app. We are using external uploads using Dropbox and it was not working.
This is how we fixed it. Summarizing the different reads and solutions. Please let me know if any part is not correct or does not make sense.
Starting from IE11, Windows has started assigning the security levels to the applications at the time of startup. Low-Security window and High-security window. Also starting IE11, when new popup opens, it is not a sub-window of the main browser window. Instead, it is a whole new IE11 instance with different security level assigned to it. Usually, the external upload mechanism works using the cross window messaging feature of JavaScript. If that does not work, external uploads do not work. As per windows security standards, a low-security window cannot send a message to the high-security window. Taking a step back and looking at our windows machine, they are shipped by our Internal team. By the default, all our domain web applications are added to trusted sites in our windows machines. But external upload links like Dropbox is not added to the trusted sites. So when you open Our App in IE11, windows automatically marks IE11 window as High-security window. Now, when you try to upload a design file through Dropbox because Dropbox is not trusted site, the new popup that gets created is a new IE11 instance with low-security level. Due to this, after the Dropbox window opened, it loses connection with the parent window that is Our App. This is causing the issue with External uploads
Either add both yoursite.com and dropbox.com to trusted sites in IE11 through Internet Options > Security > Trusted Sites or remove them both.
Enable Protected Mode in IE11 by marking Enable Protected Mode in IE11 through Internet Options > Security > Enable Protected Mode and then restart the browser.
This means it is not a real issue for our Customers. If it’s not working for them, it is either due to the reason, either of the sites is added to the trusted sites list but not both.
window.open from add-in in Windows Outlook using WebView1 returns null window #1525
Comments
westconference commented Nov 26, 2020 •
Calling window.open from an add-in on versions of Windows Outlook that use WebView1 (old Edge, specifically Office for 365 16.0.13328.20350) is seen to return null rather than a reference to the newly opened window. The new window is opened however no reference is returned to it. Further the new window will have window.opener set to undefined and its window.parent will refer to itself, effectively meaning it is not possible to communicate between the two windows.
This does not happen if window.open is invoked from JavaScript console of a browser. Just seeing it occur from within the add-in JavaScript context in this WebView1 Windows Outlook. Does not occur on Outlook Mac, in OWA or on Outlook using WebView2.
- openedWindow will be null rather than a reference to the window that was opened.
I’ve checked for various pop-up settings etc that might be blocking this but haven’t got any to work. Tried putting all involved sites into Trusted Sites or Internet Sites with Protected mode On or Off but no difference.
Expected Behavior
window.open should return reference to window that was created when called from inside the add-in.
Current Behavior
window.open returns null when called from inside the add-in on Outlookfor 365 using WebView1.
Steps to Reproduce, or Live Example
- Create a simple ExecuteFunction add-in that on launch opens a window using window.open.
- Add-in should store the result of window.open so it can then be examined.
— Examine either using a script debugger to attach to the code at this point or write a message to the Outlook status bar indicating if window.open result was null or not.
Context
I want to be able to open a window that i can post messages to from my add-in to give a Windows Outlook desktop user some detailed information about what the UI-less add-in is doing. The approach was to open a window and then pass text to it using postMessage on the returned window reference from opening it which works on some instances of Outlook e.g. WebView2, Outlook for Mac, but is not working with WebView1.
Your Environment
- Platform [PC desktop, Mac, iOS, Office on the web]: PC Desktop Windows Outlook
- Host [Excel, Word, PowerPoint, etc.]: Outlook
- Office version number: 16.0.13328.20350 (64-bit) Outlook for 365
- Operating System: Windows
The text was updated successfully, but these errors were encountered:
Форум
Справочник
window.open
Синтаксис
Аргументы
Описание, примеры
Метод open создает новое окно браузера , аналогично команде «Новое окно» в меню браузера. Обычно это не вкладка, а именно новое окно, но в некоторых браузерах можно настроить то или иное поведение явным образом.
Если параметр strUrl — пустая строка, то в окно будет загружен пустой ресурс about:blank.
В любом случае, загрузка осуществляется асинхронно. Создается пустое окно, загрузка ресурса в которое начнется уже после завершения исполнения текущего блока кода.
Связь между окнами
Метод open возвращает ссылку на новое окно, которая служит для обращения к нему и вызову его методов, если это соответствует ограничениям безопасности Same Origin.
Если окно с именем winName уже существует, то вместо открытия нового окна, strUrl загружается в существующее, ссылка на которое возвращается. При этом строка параметров не применяется.
В случае, когда окно открыть не удалось, например, оно заблокировано штатными Popup-blocker’ами Firefox/IE — вызов open вернет null.
Проверяйте его, если не хотите лишних ошибок в своих скриптах.
Указание пустого strUrl для существующего имени окна — удобный способ получить ссылку на это окно без его перезагрузки.
Если вы хотите открывать новое окно при каждом вызове open() — используйте для winName специальное значение ‘_blank’.
Строка параметров
Необязательная строка параметров состоит из списка разделенных запятой настроек нового окна. После открытия окна их уже нельзя будет изменить.
Если строки параметров нет или она пустая, то для нового окна будут взяты параметры по умолчанию.
Если строка параметров указана, то не перечисленные в ней параметры будут отключены(кроме titlebar/close). Поэтому включите в ней свойства, которые нужны.
Если в параметрах не указаны размеры, то новое окно будет по размеру такое же, как последнее открытое.
Если не указана позиция нового окна, то оно откроется со сдвигом в 20-30 пикселей (зависит от браузера) от последнего открытого окна.
Такой сдвиг позволяет посетителю заметить, что открылось новое окно.
Если текущее окно максимизировано, то сдвига не будет: новое тоже будет максимизировано.
Основные кроссбраузерные параметры
Параметры, касающиеся элементов управления окна, могут быть жестко установлены в конфигурации браузера. В этом случае их указание в параметрах open() не даст нужного эффекта.
left/top Расстояние от левой/верхней границы окна операционной системы до границы нового окна. Новое окно не может быть создано за границами экрана height/width Высота/ширина в пикселях внутренности нового окна, включая полосы прокрутки, если они есть. Минимальное значение: 100 menubar Если этот параметр установлен в yes, то в новом окне будет меню. toolbar Если этот параметр установлен в yes, то в новом окне будет навигация (кнопки назад, вперед и т.п.) и панель вкладок location Если этот параметр установлен в yes, то в новом окне будет адресная строка directories Если этот параметр установлен в yes, то в новом окне будут закладки/избранное status Если этот параметр установлен в yes, то в новом окне будет строка состояния resizable Если этот параметр установлен в yes, то пользователь сможет изменить размеры нового окна. Рекомендуется всегда устанавливать этот параметр. scrollbars Если этот параметр установлен в yes, то новое окно при необходимости сможет показывать полосы прокрутки