javascript – 将消息发送到后台脚本
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 将消息发送到后台脚本,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2496字,纯文字阅读大概需要4分钟。
内容图文
我正在尝试实施一个屏幕共享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);
解决方法:
您不能简单地使用消息传递,就像在任意网页代码的内容脚本中使用它一样.
文档中有两个与网页通信的指南,分别对应两种方法:(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 */
}
);
内容总结
以上是互联网集市为您收集整理的javascript – 将消息发送到后台脚本全部内容,希望文章能够帮你解决javascript – 将消息发送到后台脚本所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。