2

I use my nodejs server with passport to provide 3rd party auth. I setup a WebView on my Anrdroid client to load the following html:

<!DOCTYPE html>
<html>
<head>
    <script src="file:///android_asset/oauth.js" type="text/javascript"></script>
</head>

<body>
</body>

</html>

With this javascript:

Android.callit('Loaded javascript file');

window.addEventListener('message', function(event) {
  Android.callit('got message event');

  authWindow.close();
}, false);

var authWindow = window.open("https://myserver/twitter/signin", "");

After successful auth to a third party server my nodejs server redirects to a page like this:

<html>
  <head>
    <script>window.opener.postMessage({"auth":true}, '*');</script>
  </head>
  <body>
  </body>
</html>

Here is my Activity that starts the webview:

public class OAuthActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.oauth);

        WebView webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.addJavascriptInterface(new JSInterface(), "Android");
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedSslError(WebView webView, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        webView.loadUrl("file:///android_asset/oauth.html");
    }

    public class JSInterface {
        @JavascriptInterface
        public void callit(String with) {
            Log.i("TEST", with);
        }
    }
}

So why is the 'message' event never firing?

As a note I have done this in a browser and it works fine. Just not when I try and use it in an android webview.

lostintranslation
  • 23,756
  • 50
  • 159
  • 262
  • Did you manage to solve this? I'm stuck on the same problem. I'm using postMessage to implement crossPageChannel communication (using Google Closure) and I see the postMessage calls but the 'message' event isn't firing – Kesty Oct 22 '15 at 11:57

1 Answers1

1

Above code will work fine if you add escape characters in above JSON as

window.opener.postMessage({\"auth\":true}, \"*\");
Ajay Sivan
  • 2,807
  • 2
  • 32
  • 57
Kashif Ilyas
  • 136
  • 1
  • 2
  • 7
  • Here's a comprehensive example complete with a download link to a working example: https://stackoverflow.com/questions/41753104/how-do-you-use-webmessageport-as-an-alternative-to-addjavascriptinterface/60292598#60292598 – user2288580 Feb 28 '20 at 08:15