Нужна помощь со сценарием всплывающего окна jquery/javascript - появляется странная ошибка в Internet Explorer
-
21-08-2019 - |
Вопрос
Я пытаюсь создать сценарий jquery, который откроет новое окно браузера (всплывающее окно) для почтового приложения (пользователь может дважды щелкнуть письмо, и оно откроется в новом окне).
Это не особенно сложно.Моя проблема в том, что я хочу отслеживать открытые окна, чтобы, если пользователь дважды щелкнет по одному и тому же почтовому элементу во второй раз, он просто установит фокус на уже открытом всплывающем окне, а не перезагрузит его.
У меня это работает в Firefox, но Internet Explorer возвращает следующую ошибку:
Line: 51
Error: The interface is unknown.
В частности, это происходит, когда пользователи закрыли всплывающее окно, а затем дважды щелкнули почтовый элемент, чтобы открыть его снова.
Мои навыки работы с javascript/jquery в лучшем случае элементарны, поэтому я надеюсь, что кто-нибудь здесь сможет мне помочь.Вот код скрипта.
(function($)
{
var _popupTracker = {}
var _popupCounter = 0;
$.fn.openPopupWindow = function(options)
{
var defaults = {
height: 600, // sets the height in pixels of the window.
width: 600, // sets the width in pixels of the window.
toolbar: 0, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
scrollbars: 0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
status: 0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
resizable: 1, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
left: 0, // left position when the window appears.
top: 0, // top position when the window appears.
center: 0, // should we center the window? {1 (YES) or 0 (NO)}. overrides top and left
createnew: 0, // should we create a new window for each occurance {1 (YES) or 0 (NO)}.
location: 0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
menubar: 0 // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
};
var options = $.extend(defaults, options);
var obj = this;
// center the window
if (options.center == 1)
{
options.top = (screen.height - (options.height + 110)) / 2;
options.left = (screen.width - options.width) / 2;
}
var parameters = "location=" + options.location +
",menubar=" + options.menubar +
",height=" + options.height +
",width=" + options.width +
",toolbar=" + options.toolbar +
",scrollbars=" + options.scrollbars +
",status=" + options.status +
",resizable=" + options.resizable +
",left=" + options.left +
",screenX=" + options.left +
",top=" + options.top +
",screenY=" + options.top;
// target url
var target = obj.attr("href");
// test if popup window is already open, if it is, just give it fokus.
var popup = _popupTracker[target];
if (options.createnew == 0 && popup !== undefined && !popup.closed)
{
popup.focus();
}
else
{
var name = "PopupWindow" + _popupCounter;
_popupCounter++;
// open window
popup = window.open(target, name, parameters);
_popupTracker[target] = popup;
_popupTracker[target].focus();
}
return false;
};
})(jQuery);
Строка кода, которая выдает мне ошибку:
if (options.createnew == 0 && popup !== undefined && !popup.closed)
Спасибо, Эгиль.
ОБНОВЛЯТЬ: Оказывается, на самом деле это особенность IE8, по крайней мере, версии бета-версии Windows 7.Выложил тестовую страницу(http://egil.dk/popuptest/popup-source.htm), и, похоже, он работает так, как ожидалось от моих коллег в IE7.Эх, время потрачено зря!
ОБНОВЛЕНИЕ 2: Наверное, стоит рассказать, как воспроизвести ошибку.Идти к http://egil.dk/popuptest/popup-source.htm, нажмите на одну из ссылок, т.е.«что-то 1», после завершения загрузки всплывающего окна вернитесь к родительскому окну и снова щелкните ту же ссылку.На этот раз всплывающее окно просто снова получит фокус и НЕ перезагружается (это намеренно и то, чего я хочу).Теперь закройте всплывающее окно и снова нажмите на ту же ссылку.Это приводит к ошибке в бета-версии IE8.В Firefox он корректно открывается.
Решение
Единственное, что я заметил, это то, что в настройках по умолчанию после строки меню стоит дополнительная запятая.После удаления последней запятой у меня в IE7 все заработало.Какая версия, если IE вызывает эту проблему?
Другие советы
Кажется, у меня работает следующее.Если кто-то может это улучшить, пожалуйста, сделайте!
В Firefox всплывающее окно получает фокус, только если оно открыто.В IE8 обнаруживается ошибка «интерфейс неизвестен», и вместо этого всплывающее окно закрывается и открывается снова.Во всех случаях строка window.open загружает текущую «страницу» во всплывающее окно.
var bigimg; // set this variable outside the function so the first time // the popup opens, bigimg is a defined variable and the if's don't choke. function popupbigpic(page) { try { if(window.focus && bigimg) bigimg.focus(); } catch(err) { if(bigimg) bigimg.close(); } bigimg = window.open(page,"popup","width=670,height=665,toolbar=no"); }
У меня была проблема с IE 8: window.open не работал, я просто заменил имя окна на нулевое, идея пришла из http://msdn.microsoft.com/en-us/library/ms536651.aspx
window.open ("sample.htm", null, "height = 200, width = 400, status = yes, wans tool = no, menubar = no, location = no");