Search code examples
androidionic-frameworkcapacitorcapacitor-plugin

It is possible to store data on the Android Webview Window Object at start with Capacitor/Ionic?


I have some configuration variables that depend on which flavor the Android App is using, including some auth variables that are needed for the angular app start up.

I need to write some of that data into a global const in the window object but I do not find any way to do it.

I have tried creating a Capacitor Plugin and calling

override fun load() {
    this.bridge.webView.evaluateJavascript("const __myTest = 'hello world'", null);
}

or with

override fun handleOnStart() {
  super.handleOnStart()
  this.bridge.webView.evaluateJavascript("const __myTest = 'hello world'", null);
}

But even when that part is called, it does not set anything (probably the webview is not defined at that time)

Is this even possible? I do not want to define a plugin call because I would need to change all the initialization of the app and I am trying to prevent that.


Solution

  • For creating a global object/variable you have to put it on window object, or use var instead of const.

    Then, you can use this.bridge.eval("window.__myTest = 'hello world';", null);, which runs evaluateJavascript under the hood but on main thread.