Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use playwright for WebRTC P2P DataChannel testing
const { firefox, webkit, chromium } = require("playwright");
(async () => {
// webkit x webkit can not be tested. no host-candidates appears by restriction
const b1 = await setup(webkit);
const b2 = await setup(firefox);
const offer = await b1.page.evaluate(async () => {
const pc = window.pc = new RTCPeerConnection();
const dc = window.dc = pc.createDataChannel("x");
window.msgs = [];
dc.onmessage = ev => (window.msgs.push(ev.data));
const promise = new Promise(resolve => {
pc.onicecandidate = ev => {
if (ev.candidate !== null) return;
resolve(pc.localDescription.toJSON());
};
});
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
return promise;
});
console.log(offer);
const answer = await b2.page.evaluate(async offer => {
const pc = window.pc = new RTCPeerConnection();
pc.ondatachannel = ev => (window.dc = ev.channel);
const promise = new Promise(resolve => {
pc.onicecandidate = ev => {
if (ev.candidate !== null) return;
resolve(pc.localDescription.toJSON());
};
});
await pc.setRemoteDescription(offer);
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
return promise;
}, offer);
console.log(answer);
await b1.page.evaluate(async answer => {
const pc = window.pc;
const promise = new Promise(resolve => {
pc.oniceconnectionstatechange = () => {
if (pc.iceConnectionState !== "connected") return;
resolve();
};
});
await pc.setRemoteDescription(answer);
return promise;
}, answer);
// for sure
await new Promise(r => setTimeout(r, 1000));
console.log(await b2.page.evaluate(() => {
return window.pc.iceConnectionState;
}));
console.log(await b1.page.evaluate(() => {
return window.pc.iceConnectionState;
}));
console.log(await b2.page.evaluate(() => {
return window.dc.send("Hi from b2");
}));
console.log(await b1.page.evaluate(() => {
return window.msgs;
}));
await b1.browser.close();
await b2.browser.close();
console.log("done");
})();
async function setup(launcher) {
const browser = await launcher.launch();
const context = await browser.newContext();
const page = await context.newPage();
return { browser, context, page };
}
@leader22

This comment has been minimized.

Copy link
Owner Author

leader22 commented Jan 27, 2020

  • By default, webkit can not expose host-candidates by restriction
  • Use window to hold some states
  • Use toJSON() to return RTCSessionDescription(offer or answer) from page to Node
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.