我是一个相当陌生的JavaScript,我正在创建一个扩展程序,用于保存用户数据以显示在特定页面上(Google Classroom,具体而言)。我尝试过使用localStorage,但这会将其保存到特定页面的本地存储中。我需要用户能够在Chrome中的 中保存和访问数据,我也需要在新会话中使用它。
总之,我需要三个功能。一个用于将用户数据保存到chrome.storage,一个用于从给定键的chrome.storage中获取值,另一个用于列出chrome.storage中的所有键。
的manifest.json
{
"manifest_version": 2,
"name": "AssignMe for Classroom",
"short_name": "AssignMe",
"description": "Create your own assignments on Google Classroom.",
"version": "1.0",
"browser_action": {
"default_icon": "src/icon128.png",
"default_popup": "popup.html"
},
"icons": {
"16": "src/icon16.png",
"19": "src/icon19.png",
"48": "src/icon48.png",
"128": "src/icon128.png"
},
"content_scripts": [{
"matches": ["https://classroom.google.com/*/not-turned-in/all"],
"js": ["displayBackground.js"],
"run_at": "document_end"
}],
"permissions": [
"activeTab",
"storage",
"tabs",
"<all_urls>"
]
}
popup.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="newAssignment" onsubmit="return display()">
<fieldset>
<legend><strong>New Assignment</strong></legend>
<strong>Title</strong>
<input type="text" id="title" spellcheck="false" name="title">
<br /><br />
<strong>Date</strong>
<input type="date" id="date" spellcheck="false" name="date">
<br />
<p id="demo">0</p>
<button type="button" id="do-count">Create Assignment</button>
<script src="content.js"></script>
</fieldset>
</form>
</body>
</html>
content.js
var title = document.getElementById("title").value;
var date = document.getElementById("date").value;
// Function that saves user data to chrome.storage
// Function that grabs user data from chrome.storage by key
// Function that grabs all keys from chrome.storage
答案 0 :(得分:1)
试试这个。
curAssignment = 0;
// save data (you can use .local or .sync)
function saveData() {
chrome.storage.local.set({
Data: {
["Assignment" + curAssignment]: {
Title: title,
Date: date
}
}
}, function() {console.log("Data Saved");});
curAssignment = curAssignment + 1;
}
[“Assignment”+ curAssignment]根据已保存的项目数为新项目提供唯一ID。
// load data
loadedAssignment = 0;
function loadData() {
chrome.storage.local.get(["Data"], function(results) {
while (loadedAssignment < results.Data.length) {
loadedTitle = results.Data[loadedAssignment].Title;
loadedDate = results.Date[loadedAssignment].Date;
// your code that handles the loaded data
loadedAssignment = loadedAssignment + 1;
}
curAssignment = results.Data.length;
});
}
loadData函数循环遍历chrome.storage.local中的“Data”项,并获取存储项的Title和Date。
根据StackOverflow,你可以使用
// get all items
function getAllItems() {
chrome.storage.local.get(null, function(items) {
var allKeys = Object.keys(items);
});
}
获取存储中的所有项目。
答案 1 :(得分:0)
一种更花哨的方法(设置和获取),它还可以处理错误:
public void triggerReload() throws IOException {
LOG.info("Reloading configuration");
try {
this.contextRefresher.refresh();
} catch (final BeanCreationException e) {
// DO SOMETHING USEFUL
}
LOG.info(this.jHipsterProperties.getMail().getFrom()); // <--- value is not updated
LOG.info(this.mailProperties.getHost()); // <--- value is updated
}