2011-05-17 464 views
0

好吧,我正在嘗試爲我的Chrome擴展程序設置選項。我不知道爲什麼這是失敗的,但這是我的代碼。我確定我做錯了什麼。Chrome瀏覽器擴展選項

options.html

<html> 
<head><title>PT'd Settings</title></head> 
<script type="text/javascript"> 

// Saves options to localStorage. 
function save_options() { 
    var select = document.getElementById("show"); 
    var option = select.children[select.selectedIndex].value; 
    localStorage["show"] = option; 

    // Update status to let user know options were saved. 
    var status = document.getElementById("status"); 
    status.innerHTML = "Options Saved: "+localStorage["show"]; //this shows up perfectly 
    setTimeout(function() { 
    status.innerHTML = ""; 
    }, 750); 
} 

// Restores select box state to saved value from localStorage. 
function restore_options() { 
    var favorite = localStorage["show"]; 
    if (!favorite) { 
    return; 
    } 
    var select = document.getElementById("show"); 
    for (var i = 0; i < select.children.length; i++) { 
    var child = select.children[i]; 
    if (child.value == favorite) { 
     child.selected = "true"; 
     break; 
    } 
    } 
} 

</script> 

<body onload="restore_options()"> 

When to show image: 
<select id="show"> 
<option value="load">Show on Load</option> 
<option value="click">Show on Click</option> 
</select> 

<br> 
<button onclick="save_options()">Save</button> 
<br /> 
<div id="status"></div> 
</body> 
</html> 

然後,我需要的是選擇發送到我的JavaScript注入

background.html

<script type="text/javascript"> 
chrome.tabs.getSelected(null, function(tab) { 
    chrome.tabs.sendRequest(tab.id, {set: localStorage["show"]}, function(response) { 
     document.getElementById("box").value = response.answer; //just for testing purposes 
    }); 
}); 
document.write(localStorage["show"]); //just for testing purposes 
</script> 
<div id="box"></div> 

注入的JavaScript

... 
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    alert("set "+request.set); //never even runs 
    if(request.show == "click") { 
     //calculate "found" value and send it back 
     sendResponse({answer: found}); 
    } 
}); 
... 

所以我甚至不確定background.html頁面是否可以讀取localStorage,但是我確實知道它沒有正確地向JavaScript發送任何變量。

謝謝

回答

0

我想通了!

就不得不權限添加到清單

"permissions": ["tabs"]

谷歌Chrome瀏覽器的文檔是一種弱。

+0

如果它沒有提供您需要的信息,我們應該改進它。那些文件是混淆還是缺乏? 請通過http://new.crbug.com/ – 2011-05-18 13:38:06

+0

做文件錯誤(在文檔或其他任何東西)。這是四年前。 Chrome擴展的文檔仍然非常薄弱。 – reggie 2015-05-30 08:11:27

1

我不確定我是否完全明白你的意見,但是......或許「getBackgroundPage」方法可能會引發一個燈泡?

getBackgroundPage()允許您在擴展頁面之間共享JS狀態(如果您使用node或requireJS,就像模塊一樣)...我在popup.htm中使用它來獲取並顯示任何數據background.htm已收集。從background.htm我通過擴展徽章和桌面通知提醒用戶。

希望它能幫助!

相關問題