Change the user agent of Crosswalk 13+ as webview in Cordova

醉酒当歌 提交于 2019-12-24 15:02:07

问题


I am trying to change the User Agent of Crosswalk used as webview for Cordova. I am currently using the plugin cordova-plugin-crosswalk-webview.

I am able to accomplish the customization of the user agent with vanilla Cordova with the following code:

import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends CordovaActivity
{   

    public WebSettings settings;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init();

        settings = ((WebView) super.appView.getEngine().getView()).getSettings();
        String defaultUA = settings.getUserAgentString();
        String customUA = defaultUA+" OreeganoC1";
        settings.setUserAgentString(customUA);

        loadUrl(launchUrl);
    }
}

However, when i run the app with the Crosswalk plugin it crashes due to this piece of code. Everything works perfectly without Crosswalk. I am using Cordova 5.2.0 and Crosswalk 13.

Any hints?


回答1:


I'm not sure if this is the preferred method or not, but here's what I did (using Crosswalk 14+):

  1. I added a custom preference to my config.xml:

    <preference name="xwalkUserAgent" value="Custom UA" />

  2. In Project/platforms/android/src/org/crosswalk/engine/XWalkWebViewEngine.java, I added the following code inside the class:

    public static final String PREF_USER_AGENT = "xwalkUserAgent";
    protected CordovaPreferences preferences;
    

    In the constructor, I stored the preferences:

    public XWalkWebViewEngine(Context context, CordovaPreferences preferences) {
        this.preferences = preferences;
        ...
    }
    

    Finally, in the initWebViewSettings() method, I set the User Agent:

    private void initWebViewSettings() {
        webView.setVerticalScrollBarEnabled(false);
        String xwalkUserAgent = preferences.getString(PREF_USER_AGENT, "");
        webView.setUserAgentString(xwalkUserAgent);
    }
    

Now whenever I need to change the User Agent, I can do it from config.xml.



来源:https://stackoverflow.com/questions/32199128/change-the-user-agent-of-crosswalk-13-as-webview-in-cordova

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