2017-09-05 143 views
0

我正在與提供要放入iFrame以顯示某些託管視頻播放的URL的第三方合作。postMessage()事件偵聽器不工作

  • 這是跨域
  • 他們使用JWPlayer作爲他們的首選

我要求的方式來「知道」的視頻播放完成時的球員。從閱讀看來,postMessage()回調看起來像許多人使用的......並且是第三個供應商提出的建議,並提到他們會實施。

我被給了一個測試網址,它有這個'回調'功能...看看我能否使用它。

我似乎無法從回調/偵聽器功能得到任何警報?

由於這是我第一次實現這個,我不知道這個錯誤是源於我的最終還是他們的? 我在想這可能是postMessage()函數的路徑嗎?

firebugging代碼後..我終於資助他們的JS /回調在這裏設置:

jwPI.on('complete', function(event){ 
       playbackTime= playbackTime + (jwPI.getPosition() - positionA); 
       positionA=jwPI.getPosition(); 
       parent.postMessage('EndVideo','*'); 
      }); 

我身邊的事情有簡單的事件監聽器添加像這樣:

window.addEventListener("message", function(evt) { 
     //do whatever 
     alert("VIDEO CALLBACK FIRED"); 
    }); 

我的問題是:

  1. 爲什麼這不起作用?目標/範圍問題?
  2. 我是否需要讓第三方供應商在其postMessage()回調中更新路徑? '.parent'實際指向哪裏? (如果這是一個嵌入式iFrame?),並有DIV的等等嵌套的iFrame內容?

    我的監聽器函數位於加載此iFrame的主父文件中?

  3. 我可以直接將它保留爲原樣並以某種方式更改偵聽器中的路徑/目標嗎?

回答

0

(發佈代表作者問題的答案)

這是一個jQuery和JS解決方案。請注意,jQuery方法需要在作用域中使用originalEvent。

 //jQuery approach 
     $(window).on("message onmessage", function(evt) { 
      //message 
      var targetData = evt.originalEvent.data;    
      //origin 
      var targetOrigin = evt.originalEvent.origin; 
      //check origin for security and to make Scott proud 
      if(targetOrigin !== 'https://example.com'){ 
       //no same origin, exploit attempt in process possibly 
      }   
      //do whatever 
     }); 



     //Javascript approach 
     window.addEventListener("message", function(evt) { 
      //message 
      var targetData = evt.data; 
      //source 
      var targetSource = evt.source; //iframe source message stems from - doesnt work    
      //origin 
      var targetOrigin = evt.origin; 
      if(targetOrigin !== 'https://example.com'){ 
       //no same origin, exploit attempt in process possibly 
      } 
      //do whatever 
     });