AddEventListener works on the browser but does not on Android

末鹿安然 提交于 2019-12-11 13:43:32

问题


I'm using postMessage() function to populate a message from a mobile App to a website fields. I tested it on the browser, and everything is working perfectly. However, when I tried to test on Android phone, nothing is populated.

App side:

var password = localStorage.getItem("password");
var language = localStorage.getItem("lang");
var credentials = username+'-'+password;
var msg = language+':'+username+'-'+password;
var loginWindow = window.open('https://link', '_blank', 'location=yes');

function giveMeUsername(){ 
    loginWindow.postMessage(msg, 'https://link');
    console.log('open window');
}

window.addEventListener('message', function(event) {
    alert('listener alert');
var message = event.data; 
if(message == 'giveMeUsername'){ 
    console.log('call giveMeUsernam');
giveMeUsername(); 
} 
}, false);

This line alert('listener alert'); shows alert on the browser, but when I test it on Android device (apk file), nothing is showing, and no message gets sent to the website.

Website side:

addScriptDeclaration("
    console.log('message received1:  ');
window.onload = function(){ 
window.opener.postMessage('giveMeUsername', '*'); 
console.log('message received2: '); 
};
function GetSubstringIndex(str, substring, n) {
    var times = 0, index = null;
    while (times < n && index !== -1) {
        index = str.indexOf(substring, index+1);
        times++;
    }
    return index;
}
    window.addEventListener('message', function(event) {
      console.log('message received3:  ');
      //if(event.origin !== 'http://appery.io') return;
      var message = event.data;
      console.log('message received5:  '+message);
      //var username = message.substr(0, message.indexOf('-'));
      var lang = message.slice(0,2);
      var username = message.substring(message.lastIndexOf(':')+1,message.lastIndexOf('-'));
      var password = message.substr(message.indexOf('-') + 1);    
      jQuery('input#username').val(username);
      jQuery('input#password').val(password);
       document.getElementById('loginbtn').click();
       var x = document.getElementById('loginbtn').name;
       console.log('message received6:  '+ x);
    }, false);
");
$document->addScriptDeclaration("
      console.log('message received6:  ');
");
?>

I'm baffled as I am not aware of any .apk debugging method. I only develop, test and debug on the browser, and whatever works on the browser usually works on Android.


回答1:


Two things:

On a device (handset), the Alert() function isn't supported. You must use the Cordova dialogs plugin. org.apache.cordova.dialogs

And I'd try document.addEventListener and see if that fires.



来源:https://stackoverflow.com/questions/29528870/addeventlistener-works-on-the-browser-but-does-not-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!