I have a WebView in my Nativscript Vue app but on Android, the embedded website does not have access to localStorage within the browser. This question explains how to do it for Angular. The problem was that it was unclear where the webview instance was supposed to be gotten from. Question for completeness: How do I access the WebView instance that contains the android property in order to enable local storage on it?
2 Answers
This is how I solved it in the end. I needed to access the WebView passed through the event handler in the property event.object. There is no event called onWebViewLoaded on the component since this is not Angular. Instead, we need to hook onto the loadFinished event on the WebView element.
<template>
<Page>
<WebView
src="https://www.example.com/"
@loaded="onLoaded"
/>
</Page>
</template>
<script>
export default {
methods: {
//when the webview finishes loading
onLoaded(event) {
//get the webview
const webView = event.object
//if there is android
if (webView.android) {
//enable dom storage in the webview on android
webView.android.getSettings().setDomStorageEnabled(true)
}
}
}
}
</script>
Comments
Just use Vuex combined with this plugin nativescript-localstorage. I say it's untested on Nativescript 6. I can say it works because I use it my self.
Example of the store.js
import Vue from 'vue';
import Vuex from 'vuex';
import localStorage from 'nativescript-localstorage';
const NSVuexPersistent = store => {
let storageStr = localStorage.getItem('ns-vuex-persistent');
if (storageStr) {
store.replaceState(JSON.parse(storageStr))
}
store.subscribe((mutation, state) => {
// Suscribe hook.
localStorage.setItem('ns-vuex-persistent', JSON.stringify(state));
})
};
Vue.use(Vuex);
export default new Vuex.Store({
state: {
nations: null
},
plugins: [NSVuexPersistent],
mutations: {
updateNations(state, nations) {
state.nations= nations;
}
}
});
How does your main.js looks (add this):
import store from './store';
new Vue({
store,
render: h => h('frame', [h(App)])
}).$start()
2 Comments
douira
this does not address the problem in any way. I'm asking about how to enable localStorage for a webView not how to persist nativescript state.
Steven
My fault. I misread your question. Like @Manoj said: So if you say you can't make it work with your Vue component, at least you should justify why.
loadedlistener and accesswebView.androidin Vue. It's not a limitation for Vue.loadFinishedevent is triggered on every page navigation within WebView. Using loaded event saves it, you just have to do it once for WebView.