通过弹出菜单修改本地存储,并在contentscript中使用存储的值 [英] Modify local storage via popup, and use stored values in contentscript
问题描述
我希望能够使用浏览器动作弹出窗口来访问写入/修改值到本地存储(扩展存储)。
然后,我想在内容脚本中使用存储的值。
从我读过的内容看来,我需要一个背景文件?但我不确定。
一些编码示例将非常感谢!
感谢您的帮助!
如果您使用 chrome.storage
API 。这是一个存储解决方案,可以直接从内容脚本获得。
这里是它与Chrome扩展中的 localStorage
之间的对比。
需要注意的一点很重要,它是异步的,使代码稍微比使用 localStorage
:
$ b
/ * ... * /
chrome.storage.local.get('key',function(value){
//你可以在这里使用值
});
//但不在这里,因为它会在回调之前执行
/ * ... * /
但公平地说,如果你使用背景作为数据的代理,消息传递仍然是异步的。
有人可能会说,一旦数据被传递, localStorage
就可以作为同步缓存。
但是, localStorage
对象与网页共享,这是不安全的,没有人会阻止你拥有自己的同步存储缓存,使用 chrome.storage.local.get(null,/*...*/)
并且保持与 chrome.storage.onChanged
听众。
I'm trying my hand at creating a chrome extension, but am running into a wall.
I want to be able to use the browser-action popup to write/modify values into local storage (extension storage).
Then, I want to use the stored values in a content script.
From what I've read, it looks like I need a background file? but I'm not sure.
Some coded examples would be extremely appreciated!
Thanks for your help!
You can avoid using a background page as a proxy if you use chrome.storage
API. It's a storage solution that is available from Content Scripts directly.
Here is a comparison between it and localStorage
in the context of Chrome extensions.
An important thing to note is that it's asynchronous, making code slightly more complicated than using localStorage
:
/* ... */
chrome.storage.local.get('key', function(value){
// You can use value here
});
// But not here, as it will execute before the callback
/* ... */
But to be fair, if you go with the background being the proxy for data, message passing is still asynchronous.
One can argue that once the data is passed, localStorage
works as a synchronous cache.
But that localStorage
object is shared with the web page, which is insecure, and nobody stops you from having your own synchronous storage cache, initialized once with chrome.storage.local.get(null, /*...*/)
and kept up to date with a chrome.storage.onChanged
listener.
这篇关于通过弹出菜单修改本地存储,并在contentscript中使用存储的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!