【问题标题】:phonegap - postMessage - origin securityphonegap - postMessage - 来源安全
【发布时间】:2015-09-30 08:16:24
【问题描述】:

如何检查从 PhoneGap 应用发送的 postMessage 的来源?

我在PhoneGap中设置了一个iframe:

<iframe id="receiver" src="http://example.com/receiver.html" width="90" height="90"></iframe>

在 PhoneGap javascript 中,发送消息:

var receiver = document.getElementById('receiver').contentWindow;
receiver.postMessage('from phonegap app', 'http://example.com');

在receiver.html中,一些用于接收消息的javascript:

function receiveMessage(e) { alert(e.data) }
window.addEventListener('message', receiveMessage);

为了安全,在function receiveMessage我应该检查来源:

function receiveMessage(e) { 
    if (e.origin !== "something here")
        return;
    else
        alert(e.data);

但由于消息来自 PhoneGap 应用,因此来源始终只是 file://。 检查file:// 是否可以接受安全性?还是我应该使用其他值?

如果重要,我在应用程序的 config.xml 中有 &lt;access origin="http://example.com" /&gt;

【问题讨论】:

    标签: cordova security postmessage


    【解决方案1】:

    您可以从 PhoneGap(或 Cordova)使用 InAppBrowser 加载外部内容,该内容支持注入 CSS 和 JavaScript(带有结果回调),但只能从应用程序加载到加载/外部站点,这正是您所需要的需要。

    var browser = window.open('https://example.net', '_blank', 'location=no,toolbar=no,zoom=no,hidden=yes');
    
    browser.addEventListener('loadstop', function(){
        browser.executeScript({
            code: "localStorage.getItem('key_from_external_site_localStorage')", // or file: 'appLocalInjectScript.js',
            function( values ) {
                var value = values[ 0 ];
    
                navigator.notification.alert('Value received: ' + value, null, 'Success');
            }
        })
    })
    

    ```

    【讨论】:

      【解决方案2】:

      在这种情况下,我所做的是将数据(从 Cordova 应用程序到 iframe)作为对象发送,并在该对象内设置密码。 我的实现是:

      发送消息:

      function sendMessage() {
      var receiver = document.getElementById('receiver').contentWindow;
      var data={
      pw: ‘mypassword’,
      value1: ‘first value’,
      value2:1234
      };
      receiver.postMessage(data, 'http://example.com');
      };
      

      在 iframe 中接收消息:

      function receiveMessage(e) { 
         if (e.data.pw !== ‘mypassword’){
              alert(wrong password)    //(or return)
      }
          else{
      alert(e.data.value1+e.data.value2)
      }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        • 2011-04-06
        相关资源
        最近更新 更多