我正在尝试创建一个chrome扩展,但遇到了麻烦。
我希望能够使用浏览器操作弹出窗口将值写入/修改到本地存储(扩展存储)中。
然后,我想在内容脚本中使用存储的值。
从我读到的内容来看,我似乎需要一个背景文件?但我不确定。
一些编码示例将不胜感激!
谢谢你的帮助!
如果使用chrome.storage
API,则可以避免使用后台页面作为代理。这是一个可直接从内容脚本中获得的存储解决方案。
以下是它与localStorage
在Chrome扩展上下文中的比较。
需要注意的一点是,它是异步的,使代码比使用localStorage
:稍微复杂一些
/* ... */
chrome.storage.local.get('key', function(value){
// You can use value here
});
// But not here, as it will execute before the callback
/* ... */
但公平地说,如果后台是数据的代理,那么消息传递仍然是异步的。
有人可以说,一旦数据被传递,localStorage
就可以作为同步缓存工作。
但是localStorage
对象与网页共享,这是不安全的,并且没有人阻止您拥有自己的同步存储缓存,该缓存使用chrome.storage.local.get(null, /*...*/)
初始化一次,并通过chrome.storage.onChanged
侦听器保持最新。
后台页面可以访问扩展保存的localStorage变量。您的内容脚本只能访问在特定选项卡中打开的网站的localStorage。因此,您需要将变量从后台页面发送到内容脚本。然后,内容脚本可以访问这些变量。
以下代码将localStorage变量保存在后台脚本中,然后将其发送到内容脚本中使用。
既然你要求一个编码示例,我就给你写了一个。这个项目将有一个背景页和一个内容脚本。在弹出窗口中使用localStorage将允许后台页面访问这些变量,以便在内容脚本中使用。
类似这样的东西:
background.js
// When a tab is updated
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
// When the tab has loaded
if(changeInfo.status == 'complete') {
// Query open tabs
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
// Get URL of current tab
var tabURL = tabs[0].url;
// If localStorage is not empty
if(localStorage.length != 0) {
// Set a local storage variable
localStorage.helloworld = "Hello World";
// Send message to content script
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// Send request to show the notification
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
});
});
}
});
}
});
contentscript.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// Use the local storage variable in some way
if(request.greeting == "hello") {
var hello = localStorage.helloworld;
// do something with the variable here
}
});
一旦你有了这个工作,考虑切换到chrome.storage