2011-11-01 147 views
7

我有一個的manifest.json文件看起來像這樣:爲什麼chrome.extension.getBackgroundPage()返回null?

{ 
    "name": "Zend Debugger Extension", 
    "version": "0.1", 
    "background_page": "background.html", 
    "permissions": [ 
    "cookies", "tabs", "http://*/*", "https://*/*" 
    ], 
    "browser_action": { 
    "default_title": "Launch Zend Debugger", 
    "default_icon": "icon.png", 
    "popup": "popup.html" 
    } 
} 

這裏是我的background.html

<html> 
    <script> 
    function testRequest() { 
     console.log("test Request received"); 
    } 
    </script> 
</html> 

而且我popup.html

<script> 
function debug(target) { 
    if (target.id == 'thisPage') { 
     console.log('sending request'); 
     chrome.extension.getBackgroundPage().testRequest(); 
    } 
} 
</script> 

<div onclick="debug(this)" id="thisPage">Current Page</div> 

但是,background.html頁面似乎無法訪問。當我檢查chrome.extension.getBackgroundPage()我得到一個空值

Uncaught TypeError: Cannot call method 'testRequest' of null 

:我得到這個錯誤。我認爲我在清單文件中犯了一個錯誤,但我看不出我做錯了什麼。

謝謝。

回答

1

你缺少後臺權限,看看我的Chrome擴展我的manifest.json檔案:

{ 
    "content_scripts": [ 
    { 
     "matches": ["http://*/*"], 
     "js": ["jquery.js", "asserts.js"] 
    } 
    ], 
    "name": "Test Extension", 
    "version": "1.0", 
    "description": "A test extension to inject js to a webpage.", 
    "background_page": "background.html", 
    "options_page": "options.html", 
    "browser_action": { 
    "default_icon": "icon.png", 
    "popup": "popup.html" 
    }, 
    "permissions": [ 
    "tabs", 
    "http://*/*", "https://*/*", "<all_url>", "background" 
    ] 
} 

編輯: 你確定你有在同一文件夾中的background.html文件你所有的chrome擴展文件?,如果是的話,嘗試從擴展管理頁面重新加載你的擴展,我記得曾經有一個錯誤,我的擴展沒有重新加載,所以我去了開發人員的工具爲我的背景頁面,並執行window.location.reload(true);從控制檯,修復它。請回應,如果這個工作,我會繼續研究

+0

我嘗試添加背景權限,但嘗試chrome.extension.getBackground時仍然得到空( )和腳本運行時出現相同的錯誤。實際上,我認爲後臺許可權與擴展程序在所有標籤頁關閉時是否仍在後臺運行相關:http://code.google.com/chrome/extensions/manifest.html#permissions – AntBrown

+0

您確定您有背景嗎? html文件與所有chrome擴展的文件放在同一個文件夾中,如果是,請嘗試從擴展管理頁面重新加載你的擴展,我記得有一個錯誤,我的擴展沒有重新加載,所以我去了開發人員的工具爲我的背景頁面和執行window.location.reload(true);從控制檯,修復它。請回應如果這工作,我會繼續研究。 – ElHacker

+0

重新加載擴展修復了getBackgroundPage()= null問題。謝謝。 – AntBrown

2

下面是另一個答案更多的選擇:

chrome.extension.getBackgroundPage() returns null after awhile

According to the referenced page (Difference between Event and Background Page) there is a better option to get the background while still using Event Page :

If your extension uses, extension.getBackgroundPage, switch to runtime.getBackgroundPage instead. The newer method is asynchronous so that it can start the event page if necessary before returning it.

+0

雖然這是事實,但這是一個非常非常古老的問題,它與事件頁面之前的清單版本1有關。 – Xan

+0

時代可能已經改變,但幫助我走上正軌! –