问题
Trying to build a simple Chrome extension to output the whole contents of localStorage.
How difficult should it be? Spent a few hours researching and trying, still doesn't work :(
Appreciate assistance!
For example:
function load() {
chrome.storage.local.get(null, function(items) {
var allKeys = Object.keys(items);
alert(allKeys.count);
});
}
document.addEventListener('DOMContentLoaded', () => {
load();
});
outputs 'undefined'
Some other ways I tried actually contained an object, but I couldn't do anything with it (no count/length, no JSON.stringify, no toString() etc).
Manifest:
"permissions": [
"activeTab",
"storage",
"tabs",
"http://*/*",
"https://*/*",
"chrome://favicon/"
]
How can I output the whole localStorage within my extension popup?
Please help!
回答1:
Could you try allKeys.length
?
Object.keys(items)
would return you an array. Array by default doesn't have a property count
. I think you mean length
.
If you need the webpage's local storage (the domain loaded in your tab), instead of the extension page's local storage, I don't think you can do that.
Iván Nokonoko had a nice point that you need to inject the script in order to interact with the loaded web page, however the problem is the injected script is forced to run in an isolated environment, in which you only have access to the DOM tree, but no access to the original JS environment, thus the localStorage
variable that you can get, is the one in your own isolated env, rather than the original one.
Quoted from Chrome Content Scripts API:
However, content scripts have some limitations. They cannot:
- Use variables or functions defined by web pages or by other content scripts
And I believe injecting code has the same restrication as content script.
I think this restriction is for safety consideration. It's OK to expose the DOM tree to extensions, in the worst case the extension would mess up the view. But if expose the JS env, such as the local storage to extension, then it could be dangerous, as extension is capable of accessing/tampering data.
回答2:
To show the localStorage of currently active tab, try:
chrome.tabs.executeScript({code:'JSON.stringify(localStorage)'},function(result) {
console.log(JSON.parse(result[0]));
});
Working example:
popup.html
<body>
<div id=ls></div>
<script src="popup.js"></script>
</body>
popup.js
chrome.tabs.executeScript({code:'JSON.stringify(localStorage)'}, res => {
var ls = document.querySelector("#ls"), lsObj = JSON.parse(res[0]), lsHtml = "";
for (var key in lsObj)
lsHtml += "<p>" + key + " : " + lsObj[key] + "</p>";
ls.innerHTML = lsHtml ? lsHtml : "The active tab has nothing in localStorage";
});
来源:https://stackoverflow.com/questions/48542581/chrome-extensions-chrome-storage-local-get-headache