script.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. (function (){
  2. console.log('Hello');
  3. const connectButton = document.getElementById('createConnectionBtn');
  4. connectButton.addEventListener('click', createConnection, false);
  5. })();
  6. function createConnection() {
  7. const localConnection = new RTCPeerConnection();
  8. const sendChannel = localConnection.createDataChannel('channel');
  9. const connectionInfo = {};
  10. localConnection.onicecandidate = e => {
  11. if (e.candidate) {
  12. const candidate = e.candidate.candidate;
  13. connectionInfo.candidate = candidate;
  14. const answererUrl = 'http://localhost:8080/answerer.html?connection=' + btoa(JSON.stringify(connectionInfo));
  15. const createLink = document.createElement('a');
  16. createLink.setAttribute('href', answererUrl);
  17. createLink.setAttribute('target', 'new');
  18. createLink.append('Open me ;)');
  19. document.body.append(createLink);
  20. const pollForConnection = setInterval(() => {
  21. fetch(
  22. 'http://localhost:8000/state/json'
  23. ).then(response => {
  24. if (response.status !== 200) {
  25. throw new Error('bad status ' + response.status);
  26. }
  27. return response.json();
  28. }).then(data => {
  29. if (data.description) {
  30. console.log('yes');
  31. clearInterval(pollForConnection);
  32. createRemoteConnection(data.description);
  33. }
  34. else {
  35. console.log('no');
  36. }
  37. });
  38. }, 5000);
  39. }
  40. };
  41. localConnection.createOffer().then((desc) => {
  42. connectionInfo.description = desc.sdp;
  43. localConnection.setLocalDescription(desc);
  44. });
  45. function createRemoteConnection(desc) {
  46. const remoteDesc = {
  47. type: 'answer',
  48. sdp: desc
  49. };
  50. localConnection.setRemoteDescription(remoteDesc).then((e) => {
  51. console.log(e);
  52. });
  53. }
  54. const sendButton = document.getElementById('sendDataBtn');
  55. sendButton.addEventListener('click', sendMessage, false);
  56. function sendMessage() {
  57. const messageText = document.getElementById('sendData').value;
  58. sendChannel.send(messageText);
  59. }
  60. sendChannel.onmessage = (msg) => {
  61. document.body.append(msg.data);
  62. };
  63. }