2012-11-30 25 views
4

嘗試寫使用XUL代碼中Windows臨時目錄中的文件寫入文件:無法使用XUL

function writeFile_launch_application(utility_name,utility_path) 
{ 
var data ='tasklist /nh /fi "imagename eq '+utility_name+'" | find /i "'+utility_name+'">nul && (echo alerady running) || ("'+utility_path+'")'; 
//alert(data); 
var file = Cc["@mozilla.org/file/directory_service;1"]. 
     getService(Ci.nsIProperties). 
     get("TmpD", Ci.nsIFile); 
     file.append("launch_application.bat"); 
     file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666); 

     // Then, we need an output stream to our output file. 
     var ostream = Cc["@mozilla.org/network/file-output-stream;1"]. 
         createInstance(Ci.nsIFileOutputStream); 
     ostream.init(file, -1, -1, 0); 

     // Finally, we need an input stream to take data from. 
     const TEST_DATA = data; 
     let istream = Cc["@mozilla.org/io/string-input-stream;1"]. 
         createInstance(Ci.nsIStringInputStream); 
     istream.setData(TEST_DATA, TEST_DATA.length); 

     NetUtil.asyncCopy(istream, ostream, function(aResult) { 
      if (!Components.isSuccessCode(aResult)) { 
      // an error occurred! 
      } 
     }) 
} 

但得到錯誤:

Timestamp: 11/29/2012 11:03:09 PM 
Error: ReferenceError: Cc is not defined 
Source File: chrome://myaddon/content/overlay.js 
Line: 199 

我也試過在頂部以下行添加我的代碼,但它沒有解決以上錯誤:

Components.utils.import("resource://gre/modules/NetUtil.jsm"); 

Components.utils.import("resource://gre/modules/FileUtils.jsm"); 

回答

0

當我開發我的插件,我總是試圖取代Components.utils,Components.intefacesCuCi。要做到這一點,在我的文件中的第一行是:

const { Cc, Ci, Cu } = require('chrome'); 

CcComponent.classes。現在您可以使用

Cu.import("resource://gre/modules/FileUtils.jsm"); 
Cu.import("resource://gre/modules/NetUtil.jsm"); 
+0

現在,它說:「需要是沒有定義」 – user1862780

+0

是否使用附加組件生成器?我使用它有很多問題,現在我用'cfx'開發。嘗試關閉/刷新瀏覽器並清理其緩存。 –

+0

不使用插件生成器,我直接編輯xpi文件。 – user1862780

1

Cc和Ci分別是Components.classes和Components.interfaces的別名。

取決於他們可能(或可能不)已經定義的上下文。

在任何情況下

const Cc = Components.classes; 
const Ci = Components.interfaces; 
const Cu = Components.utils; 
const Cr = Components.results; 

(你不應該標籤作爲firefox-addon-sdk你的問題)