Chrome扩展程序:重新加载页面时清除Chrome本地存储不适用于更新

问题描述

我正在研究将对DOM结构进行排序的Chrome扩展程序。在扩展名弹出窗口中,我使用的按钮将激活/取消激活排序。为了保存按钮的状态,我通过Chrome Local Storage通过以下方式保存了按钮的“状态”:

function save_button_state() {
  var buttonStateText = $("#js-toggleSorting").html();
  var buttonStateAttribute = $("#js-toggleSorting").attr("data-click-state");
  var sortMessage = $(".message").html();
  chrome.storage.local.set(
    {
      buttonStateText: buttonStateText,buttonStateAttribute: buttonStateAttribute,sortMessage: sortMessage,},function () {
      console.log(
        `Saved State is: ${buttonStateText} and Saved Attribute is: ${buttonStateAttribute} and Saved Message is: ${sortMessage}`
      );
    }
  );
}

这将保存dom节点并保留信息,以便在弹出窗口关闭时进行保存。然后,为了从本地存储中获取该信息,我使用了以下功能

function get_button_state() {
  chrome.storage.local.get(
    ["buttonStateText","buttonStateAttribute","sortMessage"],function (data) {
      $(".message").html(data.sortMessage);
      $("#js-toggleSorting").html(data.buttonStateText);
      $("#js-toggleSorting").attr(
        "data-click-state",data.buttonStateAttribute
      );
      console.log(
        `Get State is ${data.buttonStateText} and Get Attribute is ${data.buttonStateAttribute}`
      );
    }
  );
}

然后,当文档准备就绪时,我正在处理按钮onclick事件,以这种方式将dom从“排序”更改为“未排序”:

$(document).ready(() => {
  get_button_state();
  //Some Code to pass parameters from the extension to a content script
  $("#js-toggleSorting").on("click",function () {
    $(".message").html("");
    if ($(this).attr("data-click-state") == 1) {
      $(this).attr("data-click-state",0);
      $(this).html("SORT INCOMING CHATS");
      $(".message").append("<p>STATUS: NOT SORTING CHATS</p>");
      sortFunction(false);
    } else {
      $(this).attr("data-click-state",1);
      $(this).html("STOP SORTING INCOMING CHATS");
      $(".message").append("<p>STATUS: SORTING CHATS</p>");
      sortFunction(true);
    }
    save_button_state();
  });
});

然后在Chrome Extension后台js文件中,当我重新加载页面(同一页面,使用相同的URL)时,我试图清除本地存储空间:

chrome.tabs.onUpdated.addListener(function (changeInfo) {
  if (changeInfo.url === undefined) {
    chrome.storage.local.clear();
  }
});

但是显然,这不仅会在我重新加载页面时清除本地存储,而且当其中的某些更改引起弹出窗口上的许多错误行为时(基本上是在用户交互/单击时非常随机地更改按钮的文本)每次他们打开弹出窗口时)。我的问题是,仅在重新加载/刷新页面时,清除本地存储的正确方法是什么。很抱歉,这似乎很明显,但是我是Chrome扩展开发领域的新手。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)