【问题标题】:(extension)Saving the changed values when i updating the tab(扩展)更新选项卡时保存更改的值
【发布时间】:2018-06-10 05:37:29
【问题描述】:

所以,我有一个输入 popup.html。如果您输入数据,popup.js 会将数据发送到content.js,并且它已经更改了选项卡上的某些内容。但是在更新选项卡后,选项卡上的更改就消失了。您如何做到这一点,以便它们只有在将新数据输入input 时才会保留和更改?

popup.html и popup.js

var input = document.querySelector('#inp');
var text = document.querySelector("#text");
var button = document.querySelector("#btn");

btn.addEventListener('click', function() {
  var inp = input.value;

  chrome.tabs.query({active: true, currentWindow: true}, function(foundTabs) {

	const activeTab = foundTabs[0];

	chrome.tabs.sendMessage(activeTab.id, {text: inp});//sending value of input
    })
});
<input type="text" id="inp">
<button id="btn">Send</button>

content.js:

chrome.runtime.onMessage.addListener(function(request) {
     const txt  = request.text; //get input value
     chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
          //insert in html
     });
});

【问题讨论】:

    标签: javascript jquery html google-chrome-extension extension-methods


    【解决方案1】:

    为了保持所做的更改,我会使用localStorage(永久)或sessionStorage(与窗口一样长)。这样,您就可以跟踪所做的更改,并在网页更新时重新进行更改。

    例如:

    content.js

    //whenever the page is loaded/updated, check if there was a saved value
    var my_text = sessionStorage.getItem("my_text");
    if (my_text) {  // if there was, update the page accordingly.
      document.querySelector("input").value = my_text;
    }
    
    chrome.runtime.onMessage.addListener(function(message){  //when a message is received...
      my_text = message.text;
      document.querySelector("input").value = my_text;  //...update the webpage ...
      sessionStorage.setItem("my_text", my_text);  // ... and save the value
    });
    

    这样,您的更改将在页面重新加载时持续存在,直到窗口关闭。要使它们即使在窗口关闭时仍然存在,请将 sessionStorage 替换为 localStorage。

    【讨论】:

    • 所以,所有这些我都必须放入chrome.tabs.onUpdated?
    • 不,你不需要chrome.tabs.onUpdated。如果您在content_scripts 文件的content_scripts 部分声明content.js,所有代码都进入content.js 并在网页中自动加载(并重新加载)。
    【解决方案2】:

    要永久保存更改,您需要将状态保存在某处。

    为此,我建议查看the Chrome developer background page。

    您可以从后台页面向您的content script(即content.js)发送消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多