变量问题(firefox扩展)

时间:2009-08-20 15:25:02

标签: javascript variables

我尝试进行firefox扩展,显示两个按钮:1和2.当你按下button1到var path获取值时,即当前打开页面的地址,然后新标签打开变为活动状态。在这个选项卡中有button2,允许放入(innerHTML)var路径的值(第一个选项卡的这个地址)。 现在问题是:button1使用函数kuku.open()而button2使用kuku.save(),但第一个函数中的var不存在于kuku.save()

var kuku = {

open: function () {
//put current URI addres into var
var path=content.location.href;

//Create nslFile object
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath(path);

//Put file content into data variable
var data = "";
var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
                        createInstance(Components.interfaces.nsIFileInputStream);
var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].
                        createInstance(Components.interfaces.nsIConverterInputStream);
fstream.init(file, -1, 0, 0);
cstream.init(fstream, "UTF-8", 0, 0); // you can use another encoding here if you wish

let (str = {}) {
  cstream.readString(-1, str); // read the whole file and put it in str.value
  data = str.value;
}
cstream.close(); // this closes fstream

//Open editor in new Tab and select it

var tab=gBrowser.addTab("http://www.google.pl");
var newTabBrowser = gBrowser.getBrowserForTab(tab);
gBrowser.selectedTab=tab;

},


save: function () {
//Write in body address from var
content.body.innerHTML=path;
}
}

我认为,问题是因为路径是局部变量,但我不能使用全局变量。它可以工作,每个浏览器只有一个选项卡。我的意思是,当用户按下第A页上的button1和第B页上的button1时,这两个新打开的页面将具有相同值的var路径。当您按其他站点上的按钮时,它将覆盖路径的值。我希望,我不会让你感到头晕;)

有人有想法吗?

1 个答案:

答案 0 :(得分:1)

将变量放在对象中,而不是放在函数中。如果变量在函数中,则只有函数可以访问它:

var kuku = {};
kuku.path = "";

kuku.open = function () {
  kuku.path = content.location.href;
  //The rest of the code here
};


kuku.save = function () {
  content.body.innerHTML=kuku.path;
};