简体   繁体   English

如何使用JavaScript在弹出窗口中捕获事件?

[英]How to capture the event in the popup window using javascript?

I have opened an external url as popup window. 我已打开一个外部URL作为弹出窗口。

var myWindow = window.open("http://google.com/","MsgWindow","width=500,height=600");

Now, I need to check whether the user clicked the search button or not. 现在,我需要检查用户是否单击了搜索按钮。

I tried to select using jquery selectors like 我试图使用类似jquery的选择器进行选择

myWindow.$('#gbqfba').onClick(function(){
     alert('abc');
});

But, It is not working. 但是,它不起作用。 :( Can you help me.. :( 你能帮助我吗..

Thanks in advance. 提前致谢。

This can only work if both the pages are under the same domain. 仅当两个页面都在同一个域中时,此方法才有效。

This will work on your console while you are at stackoverflow.com: 当您在stackoverflow.com上时,这将在您的控制台上工作:

var myWindow = window.open("http://stackoverflow.com/","MsgWindow", "width=500","height=600");
$(myWindow).on('click', 'a', function() {alert('a')})

This won't: 这不会:

var myWindow = window.open("http://google.com/","MsgWindow", "width=500","height=600");
$(myWindow).on('click', 'a', function() {alert('a')})

Why can't you just capture the click on the search button? 您为什么不能只捕捉搜索按钮的点击?

<button type="button" id="search">Search</button>

and in your jQuery 并在您的jQuery中

$("#search").click(function(){
    var myWindow = window.open("http://google.com/","MsgWindow","width=500,height=600");

});

I don't think you can use javascript to detect events take place in a different window. 我认为您无法使用javascript来检测发生在其他窗口中的事件。 You can try, instead of using window.open(), loading the page (google.com in your case) to an iframe in a form of lightbox or similar js plugins. 您可以尝试使用lightbox或类似的js插件的形式将网页(在您的情况下为google.com)加载到iframe中,而不要使用window.open()。

Even if you do that, the browser won't let you tap into the content inside the iframe. 即使这样做,浏览器也不会允许您使用iframe中的内容。 You won't be able to detect exactly what the user clicks, but you can find out once the user has triggered a click event using this script. 您将无法准确检测到用户单击的内容,但是一旦用户使用此脚本触发了click事件,您就可以找出。

$('window').click( function(e){
    console.log('User Clicked outside the iframe');
});

$('window').blur( function(e){
    console.log('User clicked on the iframe or outside the page');
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM