我正在尝试创建一个 chrome 扩展,但我遇到了墙。
我希望能够使用浏览器操作弹出窗口将值写入/修改到本地存储(扩展存储)中。
然后,我想在内容脚本中使用存储的值。
从我读到的,看起来我需要一个背景文件?但我不确定。
一些编码示例将不胜感激!
谢谢你的帮助!
我正在尝试创建一个 chrome 扩展,但我遇到了墙。
我希望能够使用浏览器操作弹出窗口将值写入/修改到本地存储(扩展存储)中。
然后,我想在内容脚本中使用存储的值。
从我读到的,看起来我需要一个背景文件?但我不确定。
一些编码示例将不胜感激!
谢谢你的帮助!
chrome.storage
如果您使用API,您可以避免使用背景页面作为代理。它是一种可直接从 Content Scripts 获得的存储解决方案。
这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 将允许后台页面访问这些变量以在内容脚本中使用。
像这样的东西:
背景.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) {
});
});
}
});
}
});
内容脚本.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