我创建了我的第一个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>
感谢任何帮助。
答案 0 :(得分:1)
基本问题,但你去了。
显然,要做到这一点,你需要JavaScript代码。 Chrome的内容安全政策禁止使用内联代码,因此代码必须放在单独的.js
文件中(例如popup.js
)并包含在HTML中:
<html>
<head>
<script src="popup.js">
</head>
<body>
<iframe id="myURL" name="myURL" width="200" height="200"></iframe>
</body>
</html>
代码应该:
一个。从localStroage
湾在页面上找到元素
℃。分配其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
将无法找到并且未定义。
有两种方法可以解决它:
一个。将<script>
标记移动到其引用的元素下方,就像在options.html
湾将您的代码包含在侦听器中,以便为页面完全解析并为其准备好的事件。我更喜欢这个解决方案。
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("myUrl").src = localStorage.url;
});
进一步阅读:
DOMContentLoaded
event chrome.storage
API。答案 1 :(得分:0)
要获取本地存储值,您可以
savedURL = localStorage.get('url') ;
然后在jQuery中就像这样
$('#myURL').attr('src',savedURL)