2009-09-17 29 views
1

我想讓我的Firefox擴展將一個對象添加到瀏覽頁面的內容窗口中。我希望它具有與運行相同的效果:從Firefox擴展中設置頁面窗口對象中的對象?

top.myobj = {val : 3}; 

在頁面中的腳本元素內。

任何想法?

我不認爲這裏存在安全風險,因爲我只添加一個具有單個整數屬性的對象。有沒有簡單的方法從擴展代碼中獲取內容窗口對象?

回答

-1

它需要是窗口,還是它可以是文檔本身?您始終可以使用content.document引用頁面本身。或者主要內容窗口爲window.content

+0

雖然這不允許您在內容窗口中設置屬性。 – Nickolay 2009-10-12 06:40:41

2

使用

var mainWindow = window 
    .QueryInterface(Components.interfaces.nsIInterfaceRequestor) 
    .getInterface(Components.interfaces.nsIWebNavigation) 
    .QueryInterface(Components.interfaces.nsIDocShellTreeItem).rootTreeItem 
    .QueryInterface(Components.interfaces.nsIInterfaceRequestor) 
    .getInterface(Components.interfaces.nsIDOMWindow); 

mainWindow.getBrowser().addEventListener("DOMContentLoaded", 
         youreventhandler, true); 

function youreventhandler(event) { 
    if (event.originalTarget instanceof HTMLDocument) { 

     var doc = event.originalTarget; 
     //doc = the document in the just loaded window 

     var win = doc.defaultView; 

     // if it's just a frame element, then return and wait for the 
     // main event to fire. 
     if (win.frameElement) 
      return; 
     else { 
      win.myobj = { val: 3}; 
      //your other code here 
     } 
    } 
} 
+0

這可能比需要更多的代碼。如果附加組件已經在瀏覽器範圍中,就像大多數附件一樣,那麼可以調用getBrowser()來獲取瀏覽器對象: getBrowser()。addEventListener(...) – sdwilsh 2009-09-17 15:39:38

+1

不幸的是,OP沒有提供有關情況的詳情。在這種情況下,我認爲太多比太少。 – 2009-09-17 16:30:36

+0

問題是,登陸此頁面的某個人可能只是在不瞭解任何內容的情況下複製這些「很多」。所以請不要這樣做:) – Nickolay 2009-10-12 11:49:25

1

您應該使用evalInSandbox執行類似this codewindow.content上下文分配:

// |content| refers to the current tab's |window| object 
var s = new Components.utils.Sandbox(content); 
s.window = content; 
Components.utils.evalInSandbox(
    "window.wrappedJSObject.test = function() { } ", s) 

BTW,再「我不認爲存在安全風險這裏「 - 向對象添加屬性可能導致執行代碼(因爲JS有setter),所以觸摸內容總是很危險。上面的示例僅在不具有chrome權限的沙箱中觸及不安全的對象(content.wrappedJSObject),因此沒有問題。

+0

注意:「組件」對象已棄用。它很快就會被刪除。 – Lucky 2013-03-07 07:38:52

+0

恩,沒有。組件對象刪除僅限內容。它不會影響我答案中的代碼。 – Nickolay 2013-03-07 20:28:01