2013-03-19 45 views
1

我想创建一个扩展,它将在社交网络中切换音乐播放的状态。我在popup.html中有一个按钮'play/pause',并且我已经为每个页面(inject.js,内容脚本)注入了一个脚本。当某人点击popup.html中的“播放/暂停”时,社交网络的某个页面必须调用headPlayPause()函数,但它不起作用。我该怎么做才能解决它?Chrome扩展程序:如何响应内容脚本中“弹出”的操作?

popup.html:

<script src = 'popup.js'></script> 
<input type = 'button' value = "Play/Pause" id = 'stopper' /> 

popup.js:

window.onload = function() { 
    document.getElementById('stopper').onclick = function() { 
     // i don't know how correctly get tabId 
     chrome.tabs.sendMessage(241, { greeting: "hello" }, 
      function(res) { 
       // returns "sendMessage callback.. undefined" 
       alert('callback of sendMessage: ' + res) 
      }); 
    } 
} 

injection.js:

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) { 
     headPlayPause(); 
    } 
); 

对不起,我的英语:)

+0

只有内容脚本不能使用除chrome.extension以外的API的任何部分。 – dortonway 2013-03-20 18:32:28

+0

谢谢,很高兴知道。 – 2013-03-21 01:56:40

回答

2

使用chrome.tabs.query({active:true, currentWindow: true}, callback);获取当前的标签ID:

document.getElementById('stopper').onclick = function() { 
    chrome.tabs.query({ 
     active: true, 
     currentWindow: true 
    }, function(tabs) { 
     var tabId = tabs[0].id; // A window has only one active tab.. 
     chrome.tabs.sendMessage(tabId, { greeting: "hello" }, 
      function(res) { 
       alert('callback of sendMessage: ' + res); 
      } 
     }); 
    }); 
}; 

为了得到一个合理的反应,你必须调用第三个参数(sendResponse):

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) { 
     // Send a response back. For example, the document's title: 
     sendResponse(document.title); 
    } 
); 

你可以阅读更多关于延期内发送消息message passing教程。

+0

Rob W,非常感谢!对不起,我无法提高你的声誉。 – dortonway 2013-03-20 18:40:03

相关问题