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

相关问题