[英]Get value from localStorage to use in popup.html
我正在創建我的第一個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"> </head> <body> <iframe id="myURL" name="myURL" width="200" height="200"></iframe> </body> </html>
該代碼應:
一種。 從localStroage
讀取值
灣 在頁面上找到元素
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
並且該element
將是未定義的。
有兩種解決方法:
一種。 將<script>
標記移動到它所引用的元素下方,就像在options.html
所做的那樣
灣 將代碼包裝在偵聽器中,以了解頁面已完全解析並准備就緒的事件。 我更喜歡這種解決方案。
document.addEventListener("DOMContentLoaded", function() { document.getElementById("myUrl").src = localStorage.url; });
進一步閱讀:
DOMContentLoaded
事件 chrome.storage
API 。 要獲取本地存儲值,您可以執行以下操作
savedURL = localStorage.get('url') ;
然后在jQuery中是這樣的
$('#myURL').attr('src',savedURL)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.