简体   繁体   English

在关闭弹出窗口时将数据保存到chrome.storage.sync-chrome扩展

[英]save data to chrome.storage.sync on closing of popup - chrome extension

I've tried many ways but no event listener is getting triggered on/before closing of popup. 我已经尝试了很多方法,但是在关闭弹出窗口之前/之前,没有触发事件监听器。 You may find related questions on SO but nothing worked for me. 您可能会在SO上找到相关问题,但对我没有任何帮助。
Here's what I tried: 这是我尝试过的:

 chrome.runtime.onSuspend.addListener(function hello() {
        chrome.storage.sync.set({
            'somedata': 'mydata1' // didn't work
        }, function() {});
    });

addEventListener("unload", function(event) {
    chrome.storage.sync.set({
        'somedata': 'mydata2'  // didn't work
    }, function() {});
}, true);

I just want to save some data when user closes the popup. 我只想在用户关闭弹出窗口时保存一些数据。 That's all. 就这样。

It's bugged so you have to do workarounds. 它存在问题,因此您必须采取解决方法。

You'll have to save the data from the background page, so you need to pass the data to it from your popup. 您必须从后台页面保存数据,因此您需要将数据从弹出窗口传递给它。

Use chrome.runtime.connect to connect the two. 使用chrome.runtime.connect连接两者。 A port is established: whenever the data you want to save from your popup changes you can Port.postMessage() to your background page. 建立了端口:只要您要从弹出窗口中保存的数据发生更改,就可以将Port.postMessage()移至后台页面。

When the popup closes, Port.onDisconnect will fire, and your data will be ready to sync. 当弹出窗口关闭时, Port.onDisconnect将触发,您的数据将准备好进行同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM