skip to Main Content

I am trying to import Browserprint script that i have downloaded locally inside src/resources

// eslint-disable-next-line import/extensions 
import "../Resources/BrowserPrint-Zebra-1.1.250.min.js"; 
//eslint-disable-next-line import/extensions 
import "../Resources/BrowserPrint-3.1.250.min.js";

Then i am just trying to do a simple console log to check if the library is there

useEffect(() => {
  getData();
  console.log(window.BrowserPrint);
  // setupPrinter();
}, []);

I get undefined. I also tried waiting a few seconds before running the console.log() but its still undefined
Visual studio code seems to catch the library as it give me autofill suggestions. So filename and path is 100% correct.
I am not sure what i am doing wrong.

Someone who has used this library in their project or any other?

2

Answers


  1. Sometimes, libraries require the entire window to be loaded before they are accessible. Try wrapping your code inside window.onload to ensure that the library is fully loaded before you access it.

    useEffect(() => {
      window.onload = () => {
        getData();
        console.log(window.BrowserPrint);
        // setupPrinter();
      };
    }, []);
    
    Login or Signup to reply.
  2. Here’s an example of how you might adjust your code:

    import React, { useEffect } from "react";
    
    function YourComponent() {
      useEffect(() => {
        const loadScripts = async () => {
          await import("../Resources/BrowserPrint-Zebra-1.1.250.min.js");
          await import("../Resources/BrowserPrint-3.1.250.min.js");
          
          // Now that scripts are loaded, you can access the BrowserPrint object
          console.log(window.BrowserPrint);
        };
    
        loadScripts();
      }, []);
    
      return (
        // Your component's JSX
      );
    }
    
    export default YourComponent;
    

    Remember that dynamically importing scripts using import() returns a Promise, so you can use await to ensure the scripts are loaded before accessing their content.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search