如果您想要媒体流,一种方法是覆盖浏览器的PeerConnection。以下是一个示例:
在扩展清单中添加以下内容脚本:
content_scripts": [
{
"matches": ["http:
"js": ["payload/inject.js"],
"all_frames": true,
"match_about_blank": true,
"run_at": "document_start"
}
]
inject.js
var inject = '('+function() {
var origPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (origPeerConnection) {
var newPeerConnection = function(config, constraints) {
console.log('PeerConnection created with config', config);
var pc = new origPeerConnection(config, constraints);
var oldAddStream = pc.addStream;
pc.addStream = function() {
console.log("our add stream called!")
console.dir(arguments[0])
return oldAddStream.apply(this, arguments);
}
pc.ontrack = function(event) {
console.log("ontrack got a track")
console.dir(event);
}
window.ourPC = pc;
return pc;
};
['RTCPeerConnection', 'webkitRTCPeerConnection', 'mozRTCPeerConnection'].forEach(function(obj) {
if (window.hasOwnProperty(obj)) {
window[obj] = newPeerConnection;
Object.keys(origPeerConnection).forEach(function(x){
window[obj][x] = origPeerConnection[x];
})
window[obj].prototype = origPeerConnection.prototype;
}
});
}
}+')();';
var script = document.createElement('script');
script.textContent = inject;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
我在谷歌Hangouts上进行语音通话测试,发现通过pc.addStream添加了两个媒体流,通过pc.ontrack添加了一个轨道。addStream似乎是本地媒体流,
ontrack中的事件对象是RTCTrackEvent,其中包含一个streams对象。我认为这就是您要寻找的内容。
要从扩展程序的内容脚本中访问这些流,您需要创建音频元素并将“srcObject”属性设置为媒体流:例如:
pc.ontrack = function(event) {
var elm = document.getElementById("remoteStream");
if(elm == null) {
elm = document.createElement("audio");
elm.id = "remoteStream";
}
elm.srcObject = event.streams[0].clone();
document.body.appendChild(elm);
var e = CustomEvent("remoteStreamAdded");
window.dispatchEvent(e);
}
然后在您的内容脚本中,您可以这样监听该事件/访问mediastream:
window.addEventListener("remoteStreamAdded", function(e) {
elm = document.getElementById("remoteStream");
var stream = elm.captureStream();
})
通过可用的捕获流,您的内容脚本可以对其进行几乎任何操作。例如,MediaRecorder非常适合记录流,或者您可以使用peer.js或binary.js之类的工具将其流式传输到另一个源。
我没有测试过,但也应该可以覆盖本地流。例如,在inject.js中,您可以建立一些空白mediastream,覆盖navigator.mediaDevices.getUserMedia,并返回自己的mediastream而不是本地的mediastream。
这种方法在Firefox和其他一些浏览器中应该也能够工作,假设您使用扩展程序/应用程序在文档开头加载inject.js脚本。它被加载在目标库之前是使此方法生效的关键。
编辑以获取更多详细信息
编辑以获取更多更详细的信息