我正在创建我的第一个 Chrome 扩展程序,并且已经到了一个我似乎无法弄清楚的阶段。
基本上我可以选择保存,但我不知道如何检索该值以在 popup.html 中使用它
这是我的代码:
manifest.json
{
"manifest_version": 2,
"name": "My Extension",
"options_page": "options.html",
"permissions": [
"storage"
],
"description": "My Extension",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
options.js
// Save options to localStorage.
function save_options()
{
localStorage["url"] = document.getElementById("url").value;
// Let the user know the options were saved.
var status = document.getElementById("status");
status.innerHTML = "Saved OK";
setTimeout( function() { status.innerHTML = ""; }, 5000 );
}
// Populate options from from localStorage.
function load_options()
{
var url = localStorage["url"];
if (url == null) { url = ""; }
document.getElementById("url").value = url;
}
// call load_options top populate the GUI when the DOM has loaded
document.addEventListener('DOMContentLoaded', load_options);
// call save_options when the user clicks the save button
document.getElementById("save").addEventListener('click', save_options);
options.html
<html>
<head>
<head><title>My Options</title></head>
<body>
<div class="container">
<label for="url">
<p>My URL</p>
<input type="text" id="url" />
<button id="save">Save</button>
</label>
</div>
<div id="status"></div>
</body>
<script src="options.js"></script>
</html>
popup.html
<html>
<head>
</head>
<body>
<iframe src="myURL" id="myURL" name="myURL" width="200" height="200"></iframe>
</body>
</html>
这工作正常,并且在选项中您可以保存放入 url 字段中的任何内容。现在我想获取保存的值并将其作为 popup.html 中 iframe 的 src (myURL)
示例:因此,在选项中,如果您输入并保存 http://www.google.com那么在 popup.html 中,iframe 将是:
<iframe src="http://www.google.com" id="myURL" name="myURL" width="200" height="200"></iframe>
感谢任何帮助。
最佳答案
基本问题,但是就这样。
显然,要执行此操作,您需要 JavaScript 代码。 Chrome 的内容安全策略禁止内联代码,因此代码必须进入单独的
.js
文件(例如popup.js
)并包含在 HTML 中:<html> <head> <script src="popup.js"></script> </head> <body> <iframe id="myURL" name="myURL" width="200" height="200"></iframe> </body> </html>
代码应该:
a.从 localStroage
读取值
b.查找页面上的元素
c.分配其 src
属性。
// Read the value
var url = localStorage.url;
// or = localStorage["url"];
// or = localStorage.get("url");
// Find the element
var element = document.getElementById("myUrl");
// Assign the property
element.src = url;
// or .setAttribute("src", url);
当然,通过删除临时变量url
,所有这些都可以压缩在一行代码中。和element
(见下文)。
- 但是,这有一个问题。当
<script>
时,代码将执行元素被读取 - 在#myURL
之前元素被读取。因此,它会失败,如element
将不会被发现并且将是未定义的。
有两种方法可以修复它:
a.移动<script>
标签位于它所引用的元素下方,就像您在 options.html
中所做的那样
b.将您的代码包装在页面已完全解析并准备就绪的事件的监听器中。我更喜欢这个解决方案。
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("myUrl").src = localStorage.url;
});
进一步阅读:
-
DOMContentLoaded
event - HTML Storage
- 替代方案:
chrome.storage
API .
关于javascript - 从 localStorage 获取值以在 popup.html 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28166076/