我需要在页面加载时打开一个弹出窗口,而不是在每个新页面加载时我需要检查弹出窗口是否仍然存在。当加载时,存储cookie,如果用户关闭弹出窗口,它将永远不会再打开,除非用户单击打开它。
在页面加载时,如果未设置cookie,则打开弹出窗口:
var page_id = getURLParameter('pageID'),
popup_opened = readCookie('music_popup'),
musicPopup;
if(page_id !== 'music_popup' & !popup_opened){
musicPopup = window.open('?pageID=music_popup', 'musicPopup', 'height=720,width=980');
};
我需要的是对点击事件的控制 1-如果用户单击链接并且弹出窗口仍然存在,则将焦点放在弹出窗口上 如果弹出窗口关闭,则为2-,而不是用焦点打开它 我试过这段代码:
$('.c_music').click(function (event) {
event.preventDefault();
if (musicPopup !== undefined) {
musicPopup.focus();
} else {
musicPopup = window.open('?pageID=music_popup', 'musicPopup', 'height=720,width=980');
};
});
这不起作用,因为如果我在一个没有打开弹出窗口的页面中,“musicPopup”总是未定义,弹出窗口即使只是打开也会打开...
我发现了这个问题:js open popup window and acces it's element in another page建议使用此代码:
来自第1页
var popup = window.open("test.html","mypopup","width=500,height=300");
popup.document.getElementById("player").someFunction();
来自第2页
var popup = window.open('','mypopup');
// now popup is know again
popup.document.getElementById("player").someFunction();
如果在第2页加载时仍然打开弹出窗口,这可以正常工作,但是如果弹出窗口关闭而不是第2页打开一个黑色弹出窗口......
我疯了......任何帮助都会非常感激!
答案 0 :(得分:1)
我刚刚找到了解决方法 看起来窗口中是否存在windows.opener如何不存在似乎没有意义 但是可以做的是检查弹出窗口是否正在加载没有内容 正如我在上面的问题中所述,使用此代码可以在窗口打开时调用它,或者加载一个空的弹出窗口:
var popup = window.open('','mypopup');
// now popup is know again
popup.document.getElementById("player").someFunction();
如果我检查重新调用的弹出窗口是否为空,我可以再次使用所需内容进行调整。所以我的最终代码是:
var page_id = getURLParameter('pageID'),
popup_opened = readCookie('music_popup'),
popup_url = '?pageID=music_popup',
popup_name = 'musicPopup',
popup_wh = 'height=720,width=980',
musicPopup;
// open the popup if there isn't the popup_opened cookie
if(!popup_opened){
musicPopup = window.open( popup_url, popup_name, popup_wh);
};
$('.c_music').click(function(event) {
event.preventDefault();
//when the user click on a .c_music link check if popup is defined (I'm in the opener page)
if(musicPopup !== undefined) {
musicPopup.focus();
musicPopup.document.getElementById("start").click();
return false;
} else {
// I'm not in the opener page, so a call the popup again
var musicPopup = window.open('', popup_name, popup_wh) ;
// if popup doesn't exist a blank one would be opened
if(musicPopup.location == 'about:blank' ){
// load the desired content in the popup
musicPopup.location = popup_url;
return false;
}
// the popup still exist, so start the music again
musicPopup.document.getElementById("start").click();
};
});
这项工作对我的需求很好,我希望它对其他人有用。