2012-08-07 62 views
0

我需要在頁面的窗口中注入一個名爲「smth」的對象,並使用帶有nsIDOMGlobalPropertyInitializer的特定URL。有什麼辦法可以實現這個嗎?如果window.smth在其他頁面上返回undefined,那就沒問題了。將具有nsIDOMGlobalPropertyInitializer的對象注入到特定頁面

// currently 
init: function(aWindow) { 
    let self = this; 
    let window = XPCNativeWrapper.unwrap(aWindow); 

    if (window.location.href !== pageURL) { 
     return; 
    } 

    return { 
      // ... 
    } 
} 

現在window.smth回報XPCOM包裹nsISupports其他頁面:(

回答

1

對象,我不知道怎麼有可能,如果在所有使用這種方法,但你至少可以爲聽「內容的文檔全局創建的」通知:https://developer.mozilla.org/en-US/docs/Observer_Notifications#Documents只有注入全球

observe: function(subject, topic, data) { 
    if (topic === 'content-document-global-created' && 
     subject instanceof Ci.nsIDOMWindow) { 
     if (!subject.location.href.match(/http:\/\/example.com/)) {return;} 
     XPCNativeWrapper.unwrap(subject).myGlobal = {}; 
    } 
} 
+0

是的,這可以解決這個問題,但恐怕可能有一些麻煩與內存消耗或一些安全問題。我的意思是我們可以設置哪些道具可以讀取,哪些道具可讀可以使用nsIDOMGlobalPropertyInitializer進行寫入。我們不能使用「content-document-global-created」XPCOM事件來做到這一點(糾正我,如果我不正確)。無論如何,謝謝你的答案。 – 2012-10-10 08:17:09

+0

請嘗試以下代碼來代替我的回答中的對應行:'Object.defineProperty(XPCNativeWrapper.unwrap(subject),'nonWritableGlobal',{writable:false,value:'myConstant'});'See https:// developer .mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty以供使用。 Mozilla曾經使用'__defineGetter__',如果上述不行,你也可以嘗試,但後者已被棄用,前者應該工作。 – 2012-10-10 09:10:52

相關問題