简体   繁体   中英

How to load script in react js? script doesn't work

I wanna use video chat from https://websitebeaver.com/insanely-simple-webrtc-video-chat-using-firebase-with-codepen-demo in react. script worked well when I tried on css+js+html (no react syntax) but script doesn't work after I converted to react

script.js file located \\chatting\\public\\js\\script.js

and Video.js file located \\chatting\\src\\components\\Messages\\Video.js

Video.js (I made this when I click the button, modal opened. and then video call should work)

import React from 'react';
import { Modal, Icon } from 'semantic-ui-react';

class Video extends React.Component {
  componentDidMount() {
    const script = document.createElement('script');

    script.src = '../../../public/js/script.js';
    script.async = true;

    document.body.appendChild(script);
  }

  render() {
    return (
      <Modal trigger={<Icon name="video camera" color="grey" />}>
        <Modal.Header>VideoCall</Modal.Header>
        <Modal.Content image>
          <div className="videoChat">
            <link rel="stylesheet" type="text/css" href="css/style.css" />
            <video
              id="yourVideo"
              autoPlay
              muted
              playsInline
              className="videoChat"
            />
            <video
              id="friendsVideo"
              autoPlay
              playsInline
              className="videoChat"
            />
            <br />
            <button
              onclick="showFriendsFace()"
              type="button"
              className="btn btn-primary btn-lg"
            >
              <span
                className="glyphicon glyphicon-facetime-video"
                aria-hidden="true"
              />{' '}
              Call
            </button>
          </div>
        </Modal.Content>
      </Modal>
    );
  }
}

export default Video;

script.js

var firebaseConfig = {
  apiKey: 'I wrote this',
  authDomain: 'I wrote this',
  databaseURL: 'I wrote this',
  projectId: 'I wrote this',
  storageBucket: 'I wrote this',
  messagingSenderId: 'I wrote this',
  appId: 'I wrote this',
  measurementId: 'I wrote this'
};

firebase.initializeApp(firebaseConfig);

var database = firebase.database().ref();
var yourVideo = document.getElementById('yourVideo');
var friendsVideo = document.getElementById('friendsVideo');
var yourId = Math.floor(Math.random() * 1000000000);

var servers = {
  iceServers: [
    { urls: 'stun:stun.services.mozilla.com' },
    { urls: 'stun:stun.l.google.com:19302' },
    {
      urls: 'turn:numb.viagenie.ca',
      credential: 'I wrote this',
      username: 'I wrote this'
    }
  ]
};
var pc = new RTCPeerConnection(servers);
pc.onicecandidate = event =>
  event.candidate
    ? sendMessage(yourId, JSON.stringify({ ice: event.candidate }))
    : console.log('Sent All Ice');
pc.onaddstream = event => (friendsVideo.srcObject = event.stream);

function sendMessage(senderId, data) {
  var msg = database.push({ sender: senderId, message: data });
  msg.remove();
}

function readMessage(data) {
  var msg = JSON.parse(data.val().message);
  var sender = data.val().sender;
  if (sender != yourId) {
    if (msg.ice != undefined) pc.addIceCandidate(new RTCIceCandidate(msg.ice));
    else if (msg.sdp.type == 'offer')
      pc.setRemoteDescription(new RTCSessionDescription(msg.sdp))
        .then(() => pc.createAnswer())
        .then(answer => pc.setLocalDescription(answer))
        .then(() =>
          sendMessage(yourId, JSON.stringify({ sdp: pc.localDescription }))
        );
    else if (msg.sdp.type == 'answer')
      pc.setRemoteDescription(new RTCSessionDescription(msg.sdp));
  }
}

database.on('child_added', readMessage);

function showMyFace() {
  navigator.mediaDevices
    .getUserMedia({ audio: true, video: true })
    .then(stream => (yourVideo.srcObject = stream))
    .then(stream => pc.addStream(stream));
}

function showFriendsFace() {
  pc.createOffer()
    .then(offer => pc.setLocalDescription(offer))
    .then(() =>
      sendMessage(yourId, JSON.stringify({ sdp: pc.localDescription }))
    );
}

and index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />
    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script src="js/script.js"></script>

    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script src="js/script.js"></script>
  </body>
</html>

componentDidMount() lifecycle method is usually is used for fetching data from an API not for importing js file. Simply just import your script.js in Video.js. You should also export the functions you need in script.js and then you can call your functions in your class by adding the name you specified at the first. in code below I only export showFriendsFace() from script.js and called it in Video.js constructor:

import React from 'react';
import { Modal, Icon } from 'semantic-ui-react';
import Script from './script'


class Video extends React.Component {
  constructor(){
      super();

      Script.showFriendsFace();
  }

  render() {
    return (
      //your return code
    );
  }
}

export default Video;

and script.js should look like this:

//your script codes

function showFriendsFace() {
  console.log("Hello World!");
}

export default {showFriendsFace};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM