只是想知道谷歌浏览器是否会window.focus()
在某个时候支持。当我的意思是支持时,我的意思是让它发挥作用。对它的调用不会失败,它只是什么都不做。所有其他主流浏览器都没有这个问题:FireFox、IE6-IE8 和 Safari。
我有一个用于管理浏览器窗口的客户端类。当我第一次创建一个窗口时,窗口成为焦点,但随后尝试将焦点移到窗口上不起作用。
据我所知,这似乎是一项安全功能,可以避免烦人的弹出窗口,而且它似乎不是 WebKit 问题,因为它可以在 Safari 中使用。
我知道有人提出的一个想法是关闭窗口然后重新打开它,但这是一个可怕的解决方案。谷歌搜索表明,我似乎不是唯一对此感到沮丧的人。
为了 100% 清楚,我的意思是新窗口,而不是选项卡(选项卡不能从我读过的内容中获得焦点),并且所有打开的窗口都在同一个域中。
除了我上面提到的坏主意之外,还有其他想法和解决方法吗?
Chromium 项目中记录了一个关于此的错误,请在此处查看。感谢您发布Rich。
MyCompany = { UI: {} }; // Put this here if you want to test the code. I create these namespaces elsewhere in code.
MyCompany.UI.Window = new function() {
// Private fields
var that = this;
var windowHandles = {};
// Public Members
this.windowExists = function(windowTarget) {
return windowTarget && windowHandles[windowTarget] && !windowHandles[windowTarget].closed;
}
this.open = function(url, windowTarget, windowProperties) {
// See if we have a window handle and if it's closed or not.
if (that.windowExists(windowTarget)) {
// We still have our window object so let's check if the URLs is the same as the one we're trying to load.
var currentLocation = windowHandles[windowTarget].location;
if (
(
/^http(?:s?):/.test(url) && currentLocation.href !== url
)
||
(
// This check is required because the URL might be the same, but absolute,
// e.g. /Default.aspx ... instead of http://localhost/Default.aspx ...
!/^http(?:s?):/.test(url) &&
(currentLocation.pathname + currentLocation.search + currentLocation.hash) !== url
)
) {
// Not the same URL, so load the new one.
windowHandles[windowTarget].location = url;
}
// Give focus to the window. This works in IE 6/7/8, FireFox, Safari but not Chrome.
// Well in Chrome it works the first time, but subsequent focus attempts fail,. I believe this is a security feature in Chrome to avoid annoying popups.
windowHandles[windowTarget].focus();
}
else
{
// Need to do this so that tabbed browsers (pretty much all browsers except IE6) actually open a new window
// as opposed to a tab. By specifying at least one window property, we're guaranteed to have a new window created instead
// of a tab.
windowProperties = windowProperties || 'menubar=yes,location=yes,width=700, height=400, scrollbars=yes, resizable= yes';
windowTarget = windowTarget || "_blank";
// Create a new window.
var windowHandle = windowProperties ? window.open(url, windowTarget, windowProperties) : window.open(url, windowTarget);
if (null === windowHandle) {
alert("You have a popup blocker enabled. Please allow popups for " + location.protocol + "//" + location.host);
}
else {
if ("_blank" !== windowTarget) {
// Store the window handle for reuse if a handle was specified.
windowHandles[windowTarget] = windowHandle;
windowHandles[windowTarget].focus();
}
}
}
}
}