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