2

I'm new to JavaScript, and I wanted to connect a button I made in my HTML file to a function in a separate JavaScript file. Right now I can create a script in my HTML file and link it to the button, but I can't link it to an external JavaScript file. This is for a speech to text chat bot.

chat.html:

<div id="result"></div>
<script type="text/javascript" src="public/js/stt.js"></script>
<button onclick="startConverting();"><i class="fa fa-microphone"></i></button>

stt.js:

function startConverting () {
  if('webkitSpeechRecognition' in window){
    var speechRecognizer = new webkitSpeechRecognition();
    speechRecognizer.continuous = true;
    speechRecognizer.interimResults = true;
    speechRecognizer.lang = 'en-IN';
    speechRecognizer.start();

    var finalTranscripts = '';

    speechRecognizer.onresult = function(event){
      var interimTranscripts = '';
      for(var i = event.resultIndex; i < event.results.length; i++){
        var transcript = event.results[i][0].transcript;
        transcript.replace("\n", "<br>");
        if(event.results[i].isFinal){
          finalTranscripts += transcript;
        }else{
          interimTranscripts += transcript;
        }
      }
      r.innerHTML = finalTranscripts + '<span style="color:#999">' + interimTranscripts + '</span>';
    };
    speechRecognizer.onerror = function (event) {
    };
  }else{
    r.innerHTML = 'Your browser is not supported. If google chrome, please upgrade!';
  }
}
Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
kai
  • 31
  • 3
  • right now it tells me startConverting() is not defined – kai Jun 28 '18 at 17:31
  • Is the file actually being loaded? Can you use the browser dev tools and see that it is loaded? Can you call `startConverting` from the browser console? – rickjerrity Jun 28 '18 at 17:33
  • No it says Failed to load resource: the server responded with a status of 404 (Not Found) – kai Jun 28 '18 at 17:40
  • 1
    Then the file path must be incorrect or the file does not exist. Double check that you can access `public/js/stt.js` file in the browser directly. – rickjerrity Jun 28 '18 at 17:57

3 Answers3

0

Just do a require('./yourfile.js');

Declare all the variables that you want outside access as global variables. So instead of

var a = "hello" it will be

GLOBAL.a="hello" or just

a = "hello"

Source: Load and execute external js file in node.js with access to local variables?

Diego Vinícius
  • 2,125
  • 1
  • 12
  • 23
0

Remove this statement :-

<script type="text/javascript" src="public/js/stt.js"></script>

The best way is to create a js file and import your stt.js file from that file:-

// Load the node-import first.
require('node-import');

var variable = require('public/js/stt.js');

Use the above style and your js will run .

PHP Web
  • 257
  • 3
  • 8
-1

Add External file as foolows

<script src="myscripts.js"></script>