2013-02-23 2 views
0

Привет Я хочу, чтобы запустить функцию из родительского окна в детском окневызов функции родительского окна в дочернем окне Javascript

Но следующий код не работает

index.php

//set status message 
function setStatus($html){ 
    $("#data").html($html); 
    } 

//twitter login page handler 
function twitter(){ 
    win = window.open('twit.php','win',"width=882,height=750,toolbar=0"); 
    setStatus('proccess...'); 
    } 

//close window 
function closeWin(){ 
    win.close(); 
    } 

//open new window 
$(".twitterBtn").click(twitter); 

упрек. php

<script language="javascript" type="text/javascript"> 
window.opener.setStatus('Login with Twitter!'); 
window.opener.closeWin(); 
</script> 

У меня проблема с window.opener, не работает

Просьба предложить способ, который будет работать во всех браузерах и не конфликтует с другими кодами

Спасибо

+0

https://developer.mozilla.org/de/docs/DOM/window.postMessage – cIph3r

ответ

1

Хорошо, потребовалось некоторое время, но у меня есть рабочий пример.

Я использую postMessage для обмена информацией, однако это необходимо только для того, чтобы ребенок знал своего родителя .. но я расширил этот пример до чата родитель-ребенок. Весело:

<html> 
<head> 
    <script> 
     window.addEventListener("load",init,false); 
     window.addEventListener("message",message,false); //register postMessages 

     //we need this because master(original) and slave(=window.open) must do different actions 
     var isSlave=window.location.href.indexOf("slave=true")>0 

     //the other-window (in the slave, this is undefined, until the handshake is complete 
     var popupwindow; 
     if (!isSlave){ 
      popupwindow=window.open(window.location.href+"?slave=true", "_blank",'toolbar=0,location=0,menubar=0'); 
     } 

     // this is called from the child window, after handshake 
     function test(){ 
      var listElem = document.createElement('li'); 
      listElem.innerHTML="handshake succesful!!!!!"; 
      document.querySelector("ul").appendChild(listElem); 
     } 

     function init(){ 
      document.querySelector("button").addEventListener("click",function(){ 
         ////popupwindow.test(); //note this works only if same origin policy allows this, else use postMessages 

       //here we send the message to the other window 
       popupwindow.postMessage(document.querySelector("#inp").value,"*"); 
      },false); 


      //the timetrigger is needed, because opening and initializing the new window takes time, then we perform a handshake to let the new window know his origin 
      setTimeout(function(){ 
      if(!isSlave) 
       popupwindow.postMessage("handshake successful","*");//handsake needed for bidirectional conneciton 
      },200); 


     } 


     //called when receiving a message 
     function message(data){ 

      //needed for bidirectional message 
      if (!popupwindow){ 
       popupwindow=data.source; 
       //popupwindow.postMessage("handshake successful","*"); //send the handshake back to the origin (notification purpose only) //instead, we do test() 
       popupwindow.test(); 
      } 

      //display the message 
      var listElem = document.createElement('li'); 
      listElem.innerHTML=data.data; 
      document.querySelector("ul").appendChild(listElem); 


     } 
    </script> 
</head> 

<body> 
    <button>say hello</button> 
    <input type="text" id="inp" /> 
    <ul></ul> 
</body> 
</html> 
+0

@ clph3r Пожалуйста, объясните, как этот метод может предоставить информацию из дочернего окна родительского окна двигаться Как Вы обращаетесь к другим страницам? –

+0

как обсуждение, когда вы хотите войти в систему и отправить комментарий с учетной записью twitter –

+0

@alismith этот код реализует чат между родительским и дочерним окнами. Просто попробуйте ... Поэтому вы можете отправлять любую информацию между этими двумя окнами. – cIph3r

Смежные вопросы