检测localStorage更改javascript

时间:2019-04-17 18:47:12

标签: javascript firefox

我正在使用一个npm包“ storage-changed”,该包可以检测同一标签(“ https://www.npmjs.com/package/storage-changed”)中的localStorage更改,现在它在chrome上可以正常工作,并且能够正确检测到事件。但是,它不适用于Firefox或Microsoft Edge。

我如何使其在这些浏览器上工作?

这是npm包功能的代码

import storageUtils from 'storage-utilities'

const emit = (target, detail, options) => {
  return new Promise(() => {
    let attempts = 0

    const interval = setInterval(() => {
      if (attempts++ >= options.timeout) clearInterval(interval)

      const event = new CustomEvent(options.eventName, { detail })

      if (target[detail.key] === detail.value) {
        window.dispatchEvent(event)
        clearInterval(interval)
      }
    }, 10)
  })
}

const getEventName = (options) => {
  return options.eventName || options.targetName + 'StorageChanged'
}

const getTimeout = (options) => {
  return options.timeout ? options.timeout / 10 : 15
}

const getTarget = (storage) => {
  if (typeof storage === 'string') {
    return window[`${storage}Storage`]
  }

  return storage
}

const getTargetName = (storage) => {
  return typeof storage === 'string'
    ? storage === 'session'
      ? 'session'
      : `local`
    : storage === window.sessionStorage
      ? 'session'
      : 'local'
}

export default (storage, options) => {
  const opts = options || {}
  // Set up missing options.
  opts.targetName = getTargetName(storage)
  opts.eventName = getEventName(opts)
  opts.timeout = getTimeout(opts)

  // Get correct storage target and ref setItem.
  const target = getTarget(storage)
  const setItem = target.setItem.bind(target)
  const removeItem = target.removeItem.bind(target)

  target.setItem = (key, value) => {
    const _value = storageUtils.stringify(value)

    emit(target, { key, value: _value, _target: opts.targetName }, opts)
    setItem(key, _value)
  }

  target.removeItem = (key) => {
    emit(target, { key, _target: opts.targetName }, opts)
    removeItem(key)
  }
}

1 个答案:

答案 0 :(得分:0)

localDataStorage 界面(HTML5 localStorage API的便捷包装器)方便地在存储所在的同一页面/标签/窗口中触发更改事件事件发生了。免责声明:我是该界面的作者。它可以在FireFox和所有Chromium闪烁浏览器(Chrome,Edge,Vivaldi,Brave等)中使用

一旦安装了 localDataStorage ,此示例代码将使您看到那些更改事件:

function nowICanSeeLocalStorageChangeEvents( e ) {
    console.log(
        "subscriber: "    + e.currentTarget.nodeName + "\n" +
        "timestamp: "     + e.detail.timestamp + " (" + new Date( e.detail.timestamp ) + ")" + "\n" +
        "prefix: "        + e.detail.prefix    + "\n" +
        "message: "       + e.detail.message   + "\n" +
        "method: "        + e.detail.method    + "\n" +
        "key: "           + e.detail.key       + "\n" +
        "old value: "     + e.detail.oldval    + "\n" +
        "new value: "     + e.detail.newval    + "\n" +
        "old data type: " + e.detail.oldtype   + "\n" +
        "new data type: " + e.detail.newtype
    );
};
document.addEventListener(
    "localDataStorage"
    , nowICanSeeLocalStorageChangeEvents
    , false
);