我正在尝试实施一个屏幕共享Web应用程序,该应用程序将使用desktopCapture Chrome API在网页上显示用户屏幕。我创建了chrome扩展,并在后台运行了一个事件监听器。我的问题是当我尝试从网页发送消息到扩展名(获取userMedia id)时,我没有在扩展端收到任何内容。我也试图将getUserMedia id返回到网页以显示feed。我已经附上了我拥有的东西。感谢
清单
{
"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);
答案 0 :(得分:8)
您不能像在任意网页代码的内容脚本中使用消息一样简单地使用消息。
文档中提供了两个与网页通信的指南,分别对应两种方法:(externally_connectable) (custom events with a content script)
假设您要允许http://example.com
向您的分机发送消息。
您需要在清单中专门将该网站列入白名单:
"externally_connectable" : {
matches: [ "http://example.com" ]
},
您需要obtain a permanent extension ID。假设结果ID为abcdefghijklmnoabcdefhijklmnoabc
您的网页需要检查是否允许发送消息,然后使用预定义的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
);
}
您的扩展程序需要收听外部消息,并且可能还会查看其来源:
// 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 */
}
);