0

I'm trying to connect a my brother QL-800 label printer to a woocommerce webshop admin page

open order, click address, print it.

brother provides a javascript library (b-pac: https://www.brother.co.jp/eng/dev/bpac/sample/index.aspx ) for that, which works in the sample page, but now i want to add it to the woocommerce page.

it is a minified .js with an export, and a html with <script type="module"> import * as bpac from './bpac.js'; //....

i thought it would be easiest to get a "add js plugin" for wordpress and just copy the script (from html) into footer js, and "add as external javascript" the minified bpac.js

but i'm getting Uncaught SyntaxError: Cannot use import statement outside a module and Uncaught SyntaxError: Unexpected token 'export'

then i thought okayyyy, maybe it helps to transpile it, so i got a commonjs online transpiler and put the result as an "external javascript" instead of the original bpac.js. this yields bpac-cjs.js?ver=1.8.1:3 Uncaught ReferenceError: exports is not defined

i don't really understand the whole thing, and i'm not really used to wordpress, so if anyone could help me real quick, that would be really nice!

if you need any additional information, feel free to ask! thanks

this is the <head> of the original sample.html

(gets form input and sends it to the printing api, easy stuff)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>b-PAC 3.2 Javascript Sample for Extensions</title>

    <script type="module">
    import * as bpac from './bpac.js';
    const DATA_FOLDER = "C:\\Program Files\\Brother bPAC3 SDK\\Templates\\";
    //const DATA_FOLDER = "http://localhost/";
    //------------------------------------------------------------------------------
    //   Function name   :   DoPrint
    //   Description     :   Print, Preview Module
    //------------------------------------------------------------------------------
    window.DoPrint = async function DoPrint(strExport)
    {
        if(bpac.IsExtensionInstalled() == false)
        {
            const agent = window.navigator.userAgent.toLowerCase();
            const ischrome = (agent.indexOf('chrome') !== -1) && (agent.indexOf('edge') === -1)  && (agent.indexOf('opr') === -1)
            if(ischrome)
                window.open('https://chrome.google.com/webstore/detail/ilpghlfadkjifilabejhhijpfphfcfhb', '_blank');
            return;
        }

        try{
            const theForm = document.getElementById("myForm");
            const nItem = theForm.cmbTemplate.selectedIndex;
            const strPath = DATA_FOLDER + theForm.cmbTemplate.options[nItem].value;

            const objDoc = bpac.IDocument;
            const ret = await objDoc.Open(strPath);
            if(ret == true)
            {
                const objName = await objDoc.GetObject("objName");
                objName.Text = name;
                objName.Text = street;
                objName.Text = city;


                theForm.txtWidth.value = await objDoc.Width;

                if(strExport == "")
                {
                    objDoc.StartPrint("", 0);
                    objDoc.PrintOut(1, 0);
                    objDoc.EndPrint();
                }
                else
                {
                    const image = await objDoc.GetImageData(4, 0, 100);
                    const img = document.getElementById("previewArea");
                    img.src = image;
                }

                objDoc.Close();
            }
        }
        catch(e)
        {
            console.log(e);
        }
    }   
    </script>  
</head>

This is the bpac.js library

Don't know how much use this one is for oyu guys, or if it's important to solve the problem..?

// .... abbreviated because of char limit in posts.. probably nothing very important here anyway. if you want me to post the whole thing, please let me know. this right here is the END of the file

i(t):n(f.detail.ret)};document.addEventListener(u,r)});return n.appendMessage(f),e}static Export(i,r,u){const f="IDocument::Export",e={method:f,type:i,filePath:r,dpi:u},o=new Promise((n,i)=>{const r=u=>{document.removeEventListener(f,r),u.detail.connect==!1?i(t):n(u.detail.ret)};document.addEventListener(f,r)});return n.appendMessage(e),o}static Close(){const i="IDocument::Close",r={method:i},u=new Promise((n,r)=>{const u=f=>{document.removeEventListener(i,u),f.detail.connect==!1?r(t):n(f.detail.ret)};document.addEventListener(i,u)});return n.appendMessage(r),u}}export const IsExtensionInstalled=()=>document.body.classList.contains("bpac-extension-installed")?!0:!1

how would i add this simple thing to my woocommerce admin page? how can i write to the <head> OR include <script>s as "module" OR get that es6 import/export syntax to work with my page? i just can't quite grasp it.

devman
  • 641
  • 1
  • 8
  • 26
  • You can use add_action('admin_enqueue_scripts', 'my_enqueue_function'); to add JS files to your admin area See: https://stackoverflow.com/questions/3326967/how-to-add-custom-javascript-to-wordpress-admin or https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/ – soDub Dec 16 '19 at 23:54
  • will this add it as a module? that seems to be kind of the problem. (import/export not working) – devman Dec 17 '19 at 10:37
  • Can you send me the download link from your JS library? Or some docs for embedding? Which browser and browserversion are you using? Maybe your browser dosen't support this: https://caniuse.com/#feat=es6-module – soDub Dec 17 '19 at 14:44
  • i'm using current chrome with the "brother b-pac extension". you can download the JS library here: https://www.brother.co.jp/eng/dev/bpac/download/index.aspx (i have 3.2.031 (64-bit ver.)). it will be under Samples/JavaScript after extraction. there's also a (pretty poor) documentation in the package. i would be really really thankful if you could help me with this one <3 – devman Dec 17 '19 at 17:43
  • Hmm okay, I'm using OSX, so i can't open any files cause they are all .exe or .msi...so i think you tried this plugin for your script module: https://wordpress.org/plugins/add-admin-javascript/ maybe you can add the script with this plugin and add the bpac.js with "add_action('admin_enqueue_scripts', 'my_enqueue_function');". I think i can't do anything more for you, sry. :( – soDub Dec 17 '19 at 19:41
  • that's what i tried, and i can just add "normal" scripts with it. no idea how to do the "module" part. :/ but thanks anyway for trying! <3 – devman Dec 17 '19 at 21:12

1 Answers1

0

You can import your module in admin by doing the following:

add_action( 'admin_enqueue_scripts', function() {
    $handle  = 'ps-import-module-one-handle';
    $src     = get_stylesheet_directory_uri() . '/doPrint.js';
    $deps    = [];
    $version = '1.0.0';
    wp_enqueue_script( $handle, $src, $deps, $version, true );

} );

/**
 *Script that import modules must use a script tag with type="module", 
 * so let's set it for the script.
 */
add_filter( 'script_loader_tag', function ( $tag, $handle, $src ) {

    switch ( $handle ) {
        case 'ps-import-module-one-handle':
            return '<script type="module" src="' . esc_url( $src ) . '"></script>';
            break;

        default:
            return $tag;
            break;
    }

}, 10, 3 );

The reason I use a switch case is that it allows me to nicely add multiple handles for different modules, as in:

switch ( $handle ) {
    case 'ps-import-module-one-handle':
    case 'ps-import-module-two-handle':
    case 'ps-import-module-three-handle':

        return '<script type="module" src="' . esc_url( $src ) . '"></script>';
        break;

    default:
        return $tag;
        break;
}

but you could replace the switch statment with a simple if ():

if ( 'ps-import-module-one-handle' === $handle ) {
    return '<script type="module" src="' . esc_url( $src ) . '"></script>';
} else {
    return $tag;
}

doPrint.js:

import * as bpac from './bpac.js';
const DATA_FOLDER = "C:\\Program Files\\Brother bPAC3 SDK\\Templates\\";
//const DATA_FOLDER = "http://localhost/";
//------------------------------------------------------------------------------
//   Function name   :   DoPrint
//   Description     :   Print, Preview Module
//------------------------------------------------------------------------------
window.DoPrint = async function DoPrint(strExport)
{
    if(bpac.IsExtensionInstalled() == false)
    {
        const agent = window.navigator.userAgent.toLowerCase();
        const ischrome = (agent.indexOf('chrome') !== -1) && (agent.indexOf('edge') === -1)  && (agent.indexOf('opr') === -1)
        if(ischrome)
            window.open('https://chrome.google.com/webstore/detail/ilpghlfadkjifilabejhhijpfphfcfhb', '_blank');
        return;
    }

    try{
        const theForm = document.getElementById("myForm");
        const nItem = theForm.cmbTemplate.selectedIndex;
        const strPath = DATA_FOLDER + theForm.cmbTemplate.options[nItem].value;

        const objDoc = bpac.IDocument;
        const ret = await objDoc.Open(strPath);
        if(ret == true)
        {
            const objName = await objDoc.GetObject("objName");
            objName.Text = name;
            objName.Text = street;
            objName.Text = city;


            theForm.txtWidth.value = await objDoc.Width;

            if(strExport == "")
            {
                objDoc.StartPrint("", 0);
                objDoc.PrintOut(1, 0);
                objDoc.EndPrint();
            }
            else
            {
                const image = await objDoc.GetImageData(4, 0, 100);
                const img = document.getElementById("previewArea");
                img.src = image;
            }

            objDoc.Close();
        }
    }
    catch(e)
    {
        console.log(e);
    }
}
soderlind
  • 470
  • 3
  • 7