2011-10-21 57 views
1

所以我收集了5種不同的方法來做到這一點,其中沒有一種方法可以在面板內工作。 Firefox在阻止訪問基本任務方面效果驚人。從Firefox插件面板中獲取當前網址

這是我已經試過:

  • 嘗試1:

    var url = window.top.getBrowser().selectedBrowser.contentWindow.location.href; 
    

    錯誤:window.top.getBrowser不是一個函數

  • 嘗試2:

    var url = window.content.document.location; 
    

    錯誤:權限被拒絕訪問屬性 '文件'

  • 嘗試3:

    var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) 
           .getInterface(Components.interfaces.nsIWebNavigation) 
           .QueryInterface(Components.interfaces.nsIDocShellTreeItem) 
           .rootTreeItem 
           .QueryInterface(Components.interfaces.nsIInterfaceRequestor) 
           .getInterface(Components.interfaces.nsIDOMWindow); 
    var url = mainWindow.getBrowser().selectedBrowser.contentWindow.location.href; 
    

    錯誤:權限被拒絕類的對象創建包裝UnnamedClass

  • 嘗試4:

    var url = window.content.location.href; 
    

    錯誤:權限被拒絕訪問屬性'href'

  • 嘗試5:

    var currentWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser"); 
    var currBrowser = currentWindow.getBrowser(); 
    var url = currBrowser.currentURI.spec; 
    

    錯誤:權限被拒絕獲得財產XPCComponents.classes

這個編碼爲Chrome是一件輕而易舉的事。不知道爲什麼這對FF來說太難了。

任何人都有解決方案嗎?

+0

https://developer.mozilla.org/en/Code_snippets/Tabbed_browser&沒有ü嘗試以'alert'的網址? – linguini

+1

錯誤消息顯示您正在運行非特權代碼(嘗試3通常是正確的方法)。不允許未經授權的代碼訪問瀏覽器的用戶界面。如果你解釋你如何運行這個代碼,有人可能會告訴你爲什麼它是無特權的。 –

回答

1

我猜「Firefox插件面板」是指Addon SDK的panel模塊?

如果是這樣,你可能試圖在content script中使用這些片段。相反,你必須將事件發送到主插件的代碼(example),並在主插件的代碼中使用tabs module

require("tabs").activeTab.url 

[更新]完整的測試用例,這對我的作品:

// http://stackoverflow.com/questions/7856282/get-current-url-from-within-a-firefox-addon-panel 
exports.main = function() { 
    var panel = require("panel").Panel({ 
    contentURL: "data:text/html,<input type=button value='click me' id='b'>", 
    contentScript: "document.getElementById('b').onclick = " + 
        "function() {" + 
        " self.port.emit('myEvent');" + 
        "}" 
    }); 
    panel.port.on("myEvent", function() { 
    console.log(require("tabs").activeTab.url) 
    }) 
    require("widget").Widget({ 
    id: "my-panel", 
    contentURL: "http://www.google.com/favicon.ico", 
    label: "Test Widget", 
    panel: panel 
    }); 
}; 
+0

是的,它確實涉及面板模塊。但是,您提供的行會導致與content-proxy.js文件相關的大量錯誤,即使我將它放在主插件的代碼中。你能告訴我到底如何使用它來獲取當前的網址嗎? –

+0

@ChrisKohout:更具體的「一些錯誤」可以幫助你現在回答你;沒有它,我將不得不在附加構建器中嘗試我的代碼(稍後)。 – Nickolay

+0

@ChrisKohout:查看更新後的答案 – Nickolay

2

我想你可以使用Firefox本地對象:

var url = gBrowser.contentDocument.location;