我怎样才能得到在options.html中设置的选项?
问题描述:
我仔细阅读Google Chrome Extensions Developer's Guide,它告诉我要在localStorage中保存选项,但content_scripts
如何能够访问这些选项?我怎样才能得到在options.html中设置的选项?
样品:
我想编写脚本,针对一对夫妇域,这个脚本应该分享这些领域的一些选项。
content_scripts:
//Runs on several domains
(function(){
var option=getOptions();
//Get options which have been set in options.html
if(option){
doSome();
}
})
option_page:
<html>
<head>
<title>My Test Extension Options</title>
</head>
<body>
option: <input id="option" type="text" /><br />
<input id="save" type="submit" /><br />
<span id="tips">option saved</span>
<script type="text/javascript">
(function(){
var input=document.getElementById('option');
var save=document.getElementById('save');
var tips=document.getElementById('tips');
input.value=localStorage.option||'';
// Here localStorage.option is what I want content_scripts to get.
function hideTips(){
tips.style.visibility='hidden';
}
function saveHandler(){
localStorage.option=input.value||'';
tips.style.visibility='visible';
setTimeout(hideTips,1000);
}
hideTips();
save.addEventListener('click',saveHandler);
})();
</script>
</body>
</html>
答
我想你可以使用chrome.extensions * API创建的通信线路的到被下运行的后台页面的。扩展名,从而为您提供本地存储。
我认为这是可能的,因为Content Script文档指定chrome.extensions * API可用于内容脚本。但我从来没有试过这个。
然后,您只需在建立连接时从后台页面向内容脚本发送消息。你甚至可以发送一个包含字面对象中所有设置的消息。
Here is an example创建双向沟通,我写了早些时候。你可以实现这个或创建一个自定义的解决方案,但我认为这是你将如何实现你正在寻找的。
哦,上帝,我必须写几个文件只是为了保存一些选项,这就是为什么我更喜欢firefox上的greasemonkey。不管怎样,谢谢你。 – Rufus 2012-03-02 23:57:59
@Rufus naw,这将很容易,只是基本的JavaScript。你甚至可以复制我给链接的代码。创建一些原型方法以将本地存储作为字符串化对象发送。然后,在您的内容脚本中解析出来,并根据我提供的内容准备好,这应该只是几行代码。 – jjNford 2012-03-03 00:02:02
谢谢,我知道,我非常感谢你的帮助。但老实说,我只想写一些简单的用户脚本,并将其放在userscripts.org上。如果Chrome扩展程序写得太复杂,那么对我来说这不是一个好主意。 – Rufus 2012-03-03 01:13:16