6

讓我解釋我的問題。我目前正在開發一款谷歌瀏覽器擴展程序,它在每個網頁中都將工具欄作爲iframe插入。內容腳本中的監聽器

問題是,我需要在某些情況下隱藏工具欄,重新顯示它和類似的東西。基本上我想把我的聽衆放在我的背景頁面上,但它沒用,因爲這個頁面不能操縱對象的圖形。所以我的計劃是把這個聽衆放在一個content_script上(他可以操縱對象的圖形)。但第二個問題是,與背景頁面相反的內容腳本不是一直執行,而是隻執行一次。

所以我問自己,如果可能的話,使內容腳本聽起來像一個背景頁,通過把一個環上或類似的東西...提前

感謝。

我已經試過這樣:

的manifest.json

{ 
    "background_page" : "background.html", 
    "browser_action" : 
    { 
     "default_icon" : "images/extension.png" 
     //"popup" : "activateToolbar.html" 
    }, 
    "content_scripts": 
    [ { 
      "all_frames": true, 
      "css": ["css/yourtoolbar.css"], 
      "js": ["js/jquery.js", "js/yourtoolbar.js", "js/listener.js"], 
      "matches": ["http://*/*"], 
      "run_at": "document_end" 
    } ], 
    "permissions" : ["tabs", "unlimitedStorage", "http://*/*", "notifications"],  
    "name" : "YourToolbar", 
    "version" : "1.1", 
    "description" : "Make your own Toolbar" 
} 

toolbar.html

<!-- Close Button --> 
      <a href="javascript:hideToolbar()"><input type="image" src="images/close.png" name="close" width="18" height="18"></a> 

Tool.js

function hideToolbar() 
{ 
    chrome.extension.sendRequest({action : "hideToolbar"}); 
    window.webkitNotifications.createHTMLNotification('instantMessage.html', 'Ask Show Menu').show(); 
} 

listener.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse){ 
    if(request.action) 
    { 
     $('body').remove(); 
     console.log('Received Start'); 
     alert(request.action); 
     console.log('Received End'); 
    } 
    else 
    { 
     console.log('nothing'); 
     alert('Not For Me [listener.js]'); 
    } 
}); 

background.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 
{ 
    if(request.newTab) 
    { 
     // Create a new Tab 
     chrome.tabs.create({url: request.newTab}); 
    } 
    else if(request.newWindow) 
    { 
     // Create a new Window 
     chrome.windows.create({url: request.newWindow}); 
    } 
    else if(request.action) 
    {  
     chrome.tabs.getAllInWindow(null, function(tabs) { 
      $.each(tabs, function() { 
      chrome.tabs.sendRequest(this.id, {"action":"hideToolbar"}); 
      }); 
     }); 
    } 
}); 

但問題是,的addListener沒有阻止執行,他只是沒抓住什麼...

+0

您能否請您說明您如何將請求發送至此內容腳本? – serg 2011-03-01 16:30:33

回答

6

要從發送請求背景頁面到您需要使用的內容腳本chrome.tabs.sendRequest(而不是chrome.extension.sendRequest)並提供標籤ID。

在內容腳本中,您不需要定期創建chrome.extension.onRequest.addListener,只需創建一次,它就會永久存在。

編輯

要發送從你需要運行chrome.extension.sendRequest那裏,並添加chrome.extension.onRequest.addListener到後臺頁面內容腳本的請求。

+0

但你告訴我如何「從後臺頁面發送請求到內容腳本」 我想發送一個請求從內容腳本到後臺頁面... – Sindar 2011-03-01 17:11:45

+0

@Sindar然後你爲什麼要創建一個監聽器在一個內容腳本並從後臺頁面發送請求?然後你需要切換它。 – serg 2011-03-01 17:14:38

+0

@Serg我不確定你明白我想要什麼。要清楚,chrome.extension.sendRequest({action:「hideToolbar」});打電話給我的聽衆(內容腳本)。 這就是我想要的,但它沒有工作,在這裏沒有與背景頁面的交互。你明白了嗎? 所以我想在我的內容腳本文件「listener.js」中創建一個監聽器。 – Sindar 2011-03-01 17:21:26