Chrome扩展程序选项

时间:2011-05-17 18:46:31

标签: javascript jquery google-chrome google-chrome-extension

好的,我正在尝试为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。

由于

2 个答案:

答案 0 :(得分:1)

我不确定我是否完全了解你的情况但是......或许“getBackgroundPage”方法可能会引发一个灯泡?

getBackgroundPage()允许您在扩展页面之间共享JS状态(如果您使用了node或requireJS,有点像模块)...我在popup.htm中使用它来获取并显示我的背景中的任何数据.htm收​​集了。来自background.htm我通过扩展徽章和桌面通知提醒用户。

希望它有所帮助!

答案 1 :(得分:0)

我明白了!

只需添加清单

的权限即可

"permissions": ["tabs"]

Google Chrome的文档有点弱。