![](/img/trans.png)
[英]How do I make it so my Chrome extension will only inject a script once?
[英]How can I make a form in Chrome extension show only once?
我正在制作一個Chrome擴展程序,該擴展程序在安裝后會在popup.html窗口中要求提供API密鑰。 用戶輸入並保存API密鑰后,應在下次單擊擴展圖標時隱藏該表單,並且僅顯示該表單下方的內容。
我的popup.html中的表單如下所示:
<form action="" class="apikey" id="api">
<input type="text" id="apikey" placeholder="Please enter your API key ...">
<button type="submit" id="saveKey" form="api">Save</button>
<a class="hint" href="#">Where can I generate my API key?</a>
</form>
以下是用於隱藏表單的popup.js代碼:
$(document).ready(function() {
$('#saveKey').click(function(event) {
event.preventDefault();
$('#api').hide();
});
});
保存API密鑰的功能也位於popup.js中 :
function saveKey() {
// Get a value saved in an input
var apiKey = $("#apikey").val();
// Check that the key has been entered
if (!apiKey) {
console.log('Error: No value specified');
return;
}
// Save it using the Chrome extension storage API
chrome.storage.sync.set({'value': apiKey}, function() {
// Notify that we saved
console.log('Your API key was saved.');
});
}
隱藏表單的工作已經完成,我現在需要做的是防止下次單擊擴展圖標時顯示#api
表單,因為當前隱藏表單僅在單擊Save button
后才有效。
我不確定您將API密鑰保存在哪里,但是我假設您的其他代碼將其保存到localStorage
。
在這種情況下,將popup.js
修改為類似以下內容:
$(document).ready(function() {
var apiKey = localStorage.getItem('apiKey');
if (apiKey) { // apiKey was saved previously
$('#api').hide();
} else {
$('#saveKey').click(function(event) {
event.preventDefault();
localStorage.setItem('apiKey', $('#apikey').val());
$('#api').hide();
});
}
});
當然,如果您不是將API密鑰保存在localStorage
,而是將其保存在服務器上或其他任何東西上,則只需保存一個標志(例如apiKeySaved
)並對其進行測試。
另一個選擇(即使它不會改變對localStorage
的值進行測試的問題的核心)將具有兩個不同的HTML文檔用於彈出窗口,並讓背景頁面使用setPopup
對其進行setPopup
。 這樣做的主要好處是,您將獲得兩個單獨的文檔以實現兩個單獨的目標。 在查看HTML時,它有點干凈,但由於要添加背景頁面,因此需要做更多的工作。 setPopup
文檔在這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.