【问题标题】:How do I enable LocalStorage in a Nativescript Vue WebView?如何在 Nativescript Vue WebView 中启用 LocalStorage?
【发布时间】:2020-01-23 17:28:23
【问题描述】:

我的 Nativscript Vue 应用程序中有一个 WebView,但在 Android 上,嵌入式网站无法访问浏览器中的 localStorage。 This question 解释了如何为 Angular 做这件事。问题是不清楚应该从哪里获取 webview 实例。完整性问题:如何访问包含 android 属性的 WebView 实例以启用本地存储?

【问题讨论】:

  • 你当然可以在Vue中添加loaded监听器并访问webView.android。这不是 Vue 的限制。
  • 对不起@douira,也许你可以尝试更好地询问或以不同的方式询问。您链接的另一个 SO 线程已经显示了它在 Android 上的启用方式。正如我已经提到的,Vue 仍然支持所有这些事件和原生对象。所以如果你说你不能让它与你的 Vue 组件一起工作,至少你应该说明原因。
  • 我现在已经澄清并回答了我的解决方案。请重新考虑这个问题与现在相比有多糟糕。
  • loadFinished 事件在 WebView 中的每个页面导航上触发。使用加载的事件保存它,您只需为 WebView 执行一次。

标签: android webview local-storage nativescript nativescript-vue


【解决方案1】:

这就是我最终解决它的方法。我需要访问通过属性event.object 中的事件处理程序传递的WebView。组件上没有名为 onWebViewLoaded 的事件,因为这不是 Angular。相反,我们需要在WebView 元素上挂钩loadFinished 事件。

<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>

【讨论】:

  • 成功了,谢谢
【解决方案2】:

只需将 Vuex 与此插件 nativescript-localstorage 结合使用即可。 我说它在 Nativescript 6 上未经测试。我可以说它有效,因为我自己使用它。

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;
        }
    }
});

你的main.js 看起来如何(添加这个):

import store from './store';

new Vue({
  store,
  render: h => h('frame', [h(App)])
}).$start()

【讨论】:

  • 这并不能以任何方式解决问题。我问的是如何为 webView 启用 localStorage,而不是如何保持 nativescript 状态。
  • 我的错。我误读了你的问题。就像@Manoj 说的:所以如果你说你不能让它与你的 Vue 组件一起工作,至少你应该证明原因。
猜你喜欢
  • 2019-10-25
  • 2016-03-13
  • 2020-11-05
  • 2020-05-13
  • 2023-03-10
  • 2020-02-17
  • 2021-02-20
  • 2019-11-12
  • 1970-01-01
相关资源
最近更新 更多