2

我想實現一個屏幕共享web應用程序,它將使用desktopCapture Chrome API在網頁上顯示用戶屏幕。我創建了Chrome擴展,並在後臺運行了一個事件監聽器。我的問題是,當我嘗試從網頁發送消息到擴展(獲取userMedia id)我沒有收到任何擴展端。我也試圖將getUserMedia id返回到網頁以顯示提要。我附上了我所擁有的。由於發送消息到後臺腳本

清單

{ 
"name": "Class Mate Manifest", 
"description": "Extension that allows for user to share their screen", 
"version": "1", 
"manifest_version": 2, 

"background": { 
    "scripts": ["background.js"] 
}, 
"permissions": [ 
"desktopCapture", 
"tabs" 
], 
"browser_action": { 
    "default_icon": "icon.png", 
"default_popup": "index.html" 
    } 
} 

background.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) { 
console.log(request.greeting); 
if(request.greeting == yes){ 
chrome.desktopCapture.chooseDesktopMedia(["screen", "window"], sendResponse); 
return true; 
} 
}); 

webpage.js

function gotStream(stream) { 
console.log("Received local stream"); 
var video = document.querySelector("video"); 
video.src = URL.createObjectURL(stream); 
localstream = stream; 
// stream.onended = function() { console.log("Ended"); }; 
} 

function getUserMediaError() { 
console.log("getUserMedia() failed."); 
} 

function onAccessApproved(id) { 
console.log(id); 
if (!id) { 
console.log("Access rejected."); 
return; 
} 


navigator.webkitGetUserMedia({ 
    audio:false, 
    video: { mandatory: { chromeMediaSource: "desktop", chromeMediaSourceId: id } } 
}, gotStream, getUserMediaError); 

} 


chrome.runtime.sendMessage({greeting: "yes"}, onAccessApproved); 

回答

6

你不能簡單地用短信以同樣的方式,你會用它的內容腳本一個任意網頁的代碼。

有文檔中提供了兩個指南與網頁,對應於兩種方法通信:(externally_connectable)(custom events with a content script)

假設你希望允許http://example.com將消息發送到您的分機。

  1. 你需要明確列入白名單,該網站在清單

    "externally_connectable" : { 
        matches: [ "http://example.com" ] 
        }, 
    
  2. 你需要obtain a permanent extension ID。假設產生的ID是abcdefghijklmnoabcdefhijklmnoabc

  3. 網頁需要檢查它允許發送消息,然後使用預先定義的ID發送:

    // Website code 
    // This will only be true if some extension allowed the page to connect 
    if(chrome && chrome.runtime && chrome.runtime.sendMessage) { 
        chrome.runtime.sendMessage(
        "abcdefghijklmnoabcdefhijklmnoabc", 
        {greeting: "yes"}, 
        onAccessApproved 
    ); 
    } 
    
  4. 擴展需要聽到外部消息並且可能還檢查其來源:

    // Extension's background code 
    chrome.runtime.onMessageExternal.addListener(
        function(request, sender, sendResponse) { 
        if(!validate(request.sender)) // Check the URL with a custom function 
         return; 
        /* do work */ 
        } 
    ); 
    
+0

是的你是對的。我能夠使用您提到的外部連接方法從我的網頁發送消息。但是現在一旦我發送消息,擴展就會正確接收消息,但不會通過回調函數發回任何消息。所以我的Chrome擴展是假設發回一個ID用於共享屏幕。但在網頁上,回調方法甚至沒有運行。有什麼想法嗎? – bigC5012 2014-09-30 02:35:31

+0

所以我修正了我之前評論中的錯誤。現在,網頁成功地向擴展程序發送消息。該擴展接收該消息並詢問用戶他們希望捕獲什麼屏幕。然後,background.js文件將正確的ID發送到網頁。一旦我的網頁在AccessAproved上運行,它無法加載視頻流並運行getUserMediaError函數。我在控制檯上輸出錯誤信息,並說NavigateUserMediaError。我不知道這個錯誤意味着什麼或者我的代碼出了什麼問題? – bigC5012 2014-09-30 21:37:15

+0

我會提出一個新的問題。 – Xan 2014-09-30 21:39:20