"ReferenceError: <function> is not defined" - javascript modules

Viewed 922

When I try to integrate the script type="module"... I get a reference error. My functions inside the "module" script are not found.

Im trying to integrate a printer into an existing webpage, the printer functionality is defined in the file "bpac.js". Its a javascript module using exports. I have tried using this code in a sample website an everything worked fine. When I use my code in the existing file I get the error. When I dont use the "module" tag everything works fine, but then I cant use the functionality provided by "bpac.js". I have a simple button that when pressed, should execute some testfunction.

<script type = "module">
import * as bpac from './bpac.js';

window.testfunc = async function testfunc() {


const doc = bpac.IDocument;
const pName = await doc.GetPrinterName();

console.log(pName);

 }

</script>

...
<button type="button" id="testen" onclick="testfunc()">test</button><br>
...

When I press the Button I get the Message: Uncaught ReferenceError: testfunc is not defined at HTMLButtonElement.onclick ((index):1)

2 Answers

You are declaring function in wrong way. Use this.

window.testfunc = async function() {

    const doc = bpac.IDocument;
    const pName = await doc.GetPrinterName();

    console.log(pName);
}

Why don't you use addEventListener to add as many listeners as you want?

  document.getElementById("testen").addEventListener('click',function () {
      console.log("Hello");
      // Add your logic inside this function
  }); 
Related