2013-03-19 59 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

相關問題