Android webview JavaScript loadurl set variable sd

2019-08-16 02:51发布

In my App I need to set a JavaScript variable on webviews for tracking purposes that the javascript will use for keeping the native analytics tracking and web tracking synced. It currently is working when I have compiledSdkVersion and targetSdkVersion set to 23.

In OnPageStarted I have this code.

String javaScript = String.format("javascript: var clientId = '%s';", nativeClientId);
webView.loadUrl(javaScript);

When I increase the compileSdkVersion and targetSdkVersion to 24, this no longer works. Javascript says the variable is not defined. When I set the versions back to 23, it works again.

I found in the WebView docs https://developer.android.com/reference/android/webkit/WebView.html#evaluateJavascript(java.lang.String, android.webkit.ValueCallback)

Compatibility note. Applications targeting N or later, JavaScript state from an empty WebView is no longer persisted across navigations like loadUrl(String). For example, global variables and functions defined before calling loadUrl(String) will not exist in the loaded page. Applications should use addJavascriptInterface(Object, String) instead to persist JavaScript objects across navigations.

How can I convert my javascript to use AddJavascriptInterface to set this clientId so that the JavaScript can still read the variable without having to change the web code?

Any suggestions or other ideas would help greatly!

0条回答
登录 后发表回答