0

Working on LWC component using Aura. Getting an issue when calling zebra print function to find printer on local network. (same code working on lightning component)

code is added in 'staticresource/module1'

enter image description here


** code is added in Module.js file as staticresource**
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.checkStringArgs=function(b,h,c){if(null==b)throw new TypeError("The 'this' value for String.prototype."+c+" must not be null or undefined");if(h instanceof RegExp)throw new TypeError("First argument to String.prototype."+c+" must not be a regular expression");return b+""};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;
$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(b,h,c){b!=Array.prototype&&b!=Object.prototype&&(b[h]=c.value)};$jscomp.getGlobal=function(b){return"undefined"!=typeof window&&window===b?b:"undefined"!=typeof global&&null!=global?global:b};$jscomp.global=$jscomp.getGlobal(this);
$jscomp.polyfill=function(b,h,c,e){if(h){c=$jscomp.global;b=b.split(".");for(e=0;e<b.length-1;e++){var k=b[e];k in c||(c[k]={});c=c[k]}b=b[b.length-1];e=c[b];h=h(e);h!=e&&null!=h&&$jscomp.defineProperty(c,b,{configurable:!0,writable:!0,value:h})}};
$jscomp.polyfill("String.prototype.startsWith",function(b){return b?b:function(b,c){var e=$jscomp.checkStringArgs(this,b,"startsWith");b+="";var h=e.length,p=b.length;c=Math.max(0,Math.min(c|0,e.length));for(var l=0;l<p&&c<h;)if(e[c++]!=b[l++])return!1;return l>=p}},"es6","es3");
var BrowserPrint=function(){function b(a,b){var d=new XMLHttpRequest;"withCredentials"in d?d.open(a,b,!0):"undefined"!=typeof XDomainRequest?(d=new XDomainRequest,d.open(a,b)):d=null;return d}function h(a,b,d){void 0===b&&(b=e.defaultSuccessCallback);void 0===d&&(d=e.defaultErrorCallback);return c(a,b,d)}function c(a,b,d){a.onreadystatechange=function(){a.readyState===XMLHttpRequest.DONE&&200===a.status?""===a.responseType?b(a.responseText):b(a.response):a.readyState===XMLHttpRequest.DONE&&(d?d(a.response):
console.log("error occurred with no errorCallback set."))};return a}var e={},k={},p=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);navigator.userAgent.indexOf("Trident/7.0");var l="http://127.0.0.1:9100/";p&&"https:"===location.protocol&&(l="https://127.0.0.1:9101/");e.Device=function(a){var m=this;this.name=a.name;this.deviceType=a.deviceType;this.connection=a.connection;this.uid=a.uid;this.version=2;this.provider=a.provider;this.manufacturer=a.manufacturer;this.readRetries="bluetooth"===
this.connection?1:0;this.sendErrorCallback=function(d){};this.sendFinishedCallback=function(d){};this.readErrorCallback=function(d){};this.readFinishedCallback=function(d){};this.send=function(d,a,f){var g=b("POST",l+"write");g&&(void 0!==m&&(void 0===a&&(a=m.sendFinishedCallback),void 0===f&&(f=m.sendErrorCallback)),c(g,a,f),g.send(JSON.stringify({device:{name:this.name,uid:this.uid,connection:this.connection,deviceType:this.deviceType,version:this.version,provider:this.provider,manufacturer:this.manufacturer},
data:d})))};this.sendUrl=function(d,a,f,e){var g=b("POST",l+"write");g&&(c(m,g,a,f),d={device:{name:this.name,uid:this.uid,connection:this.connection,deviceType:this.deviceType,version:this.version,provider:this.provider,manufacturer:this.manufacturer},url:d},null!=e&&void 0!=e&&(d.options=e),g.send(JSON.stringify(d)))};this.sendFile=function(d,a,f){if("string"===typeof d)e.loadFileFromUrl(d,function(d){m.sendFile(d,a,f)},f);else{var g=b("POST",l+"write");if(g){g.responseType="text";h(g,a,f);var c=
new FormData,n={};n.device=m;c.append("json",JSON.stringify(n));c.append("blob",d);g.send(c)}}};this.convertAndSendFile=function(d,a,b,c){c||(c={});c.action||(c.action="print");e.convert(d,this,c,a,b)};this.read=function(d,a){var f=b("POST",l+"read");f&&(void 0!==m&&(void 0===d&&(d=m.readFinishedCallback),void 0===a&&(a=m.readErrorCallback)),c(f,d,a),f.send(JSON.stringify({device:{name:this.name,uid:this.uid,connection:this.connection,deviceType:this.deviceType,version:this.version,provider:this.provider,
manufacturer:this.manufacturer}})))};this.readUntilStringReceived=function(d,a,b,e,c){c||(c="");void 0===e&&(e=this.readRetries);a=function(a,b,e,f,g){return function(c){if(c&&0!==c.length)f=0;else if(0>=f){b(g);return}c=g+c;""!==d&&-1<c.indexOf(d)?b(c):a.readUntilStringReceived(d,b,e,f-1,c)}}(this,a,b,e,c);this.read(a,b)};this.readAllAvailable=function(a,b,f){this.readUntilStringReceived("",a,b,f)};this.sendThenRead=function(a,b,f){this.send(a,function(a){return function(){a.read(b,f)}}(this),f)};
this.sendThenReadUntilStringReceived=function(a,b,f,e,c){this.send(a,function(a){return function(){a.readUntilStringReceived(b,f,e,c)}}(this),e)};this.sendThenReadAllAvailable=function(a,b,e,c){this.send(a,function(a){return function(){a.readUntilStringReceived("",b,e,c)}}(this),e)}};e.defaultSuccessCallback=function(){};e.defaultErrorCallback=function(){};e.ApplicationConfiguration=function(){this.application={version:"1.2.0.3",build_number:3,api_level:2,platform:"",supportedConversions:{}}};e.getLocalDevices=
function(a,c,d){var g=b("GET",l+"available");g&&(window.finishedFunction=function(b){response=b;response=JSON.parse(response);for(var c in response)if(response.hasOwnProperty(c)&&response[c].constructor===Array)for(arr=response[c],b=0;b<arr.length;++b)arr[b]=new e.Device(arr[b]);void 0===d?a(response):(response.hasOwnProperty(d)||(response[d]=[]),a(response[d]))},h(g,window.finishedFunction,c),g.send())};e.getDefaultDevice=function(a,c,d){var g="default";void 0!==a&&null!=a&&(g=g+"?type="+a);if(a=b("GET",l+g))window.finishedFunction=
function(a){response=a;""===response?c(null):(response=JSON.parse(response),a=new e.Device(response),c(a))},a=h(a,window.finishedFunction,d),a.send()};e.getApplicationConfiguration=function(a,c){var d=b("GET",l+"config");d&&(window.finishedFunction=function(b){response=b;""===response?a(null):(response=JSON.parse(response),a(response))},h(d,window.finishedFunction,c),d.send())};e.readOnInterval=function(a,b,d){if(void 0===d||0===d)d=1;readFunc=function(){a.read(function(c){b(c);k[a]=setTimeout(readFunc,d)},function(b){k[a]=
setTimeout(readFunc,d)})};k[a]=setTimeout(readFunc,d)};e.stopReadOnInterval=function(a){k[a]&&clearTimeout(k[a])};e.bindFieldToReadData=function(a,b,d,c){e.readOnInterval(a,function(a){""!==a&&(b.value=a,void 0!==c&&null!=c&&c())},d)};e.loadFileFromUrl=function(a,c,d){request=b("get",a);console.log("ResponseType: "+request.responseType);request.responseType="blob";h(request,c,d);request.send()};e.convert=function(a,c,d,g,f){if(a)if("string"===typeof a)e.loadFileFromUrl(a,function(b){d.fromFormat||
(d.fromFormat=a.substring(a.length-3));e.convert(b,c,d,g,f)},f);else{var k=b("POST",l+"convert");a.type&&(a.type.startsWith("image/")||a.type.startsWith("application/"))&&(d.fromFormat=a.type.toLowerCase().replace("image/","").replace("application/","").replace("x-ms-",""));if(k){k.responseType="text";h(k,function(a){g(JSON.parse(a))},f);var m=new FormData,n={};null!=d&&void 0!==d&&(n.options=d);c&&(n.device=c);m.append("json",JSON.stringify(n));m.append("blob",a);k.send(m)}}else f?f("Resource not specified"):
e.defaultErrorCallback("Resource not specified")};return e}();
window.$jscomp = $jscomp;

// http://127.0.0.1:9100/ 
// https://127.0.0.1:9101

(function() {
      debugger;
      function sayHello() {
          console.log('hello from helloModule.js');
      }
      // this makes the sayHello function available in the window     namespace
      // so we can call window.sayHello from any LWC JS file
      window.sayHello = sayHello;



window.selected_device = null;
window.devices = []; 
window.ifZebraSuccess = false;
window.labelImageOnError = null; 

window.errorCallback = function(errorMessage) {
    ifZebraSuccess = false;
    if (document.getElementById('btnPrintLabel')) {
        document.getElementById('btnPrintLabel').style.display = 'inline';
    }

    if (document.getElementById('txtPrinterError')) {
        document.getElementById('txtPrinterError').style.display = 'block';
        if(labelImageOnError) {
            printImage(labelImageOnError);
        }
    }
    else {
        console.log("PPplease configure your printer first. Please follow the link to download Installer : https://www.zebra.com/us/en/support-downloads/printer-software/by-request-software.html#browser-print");
    }

    if(document.getElementById("selected_device")) {
        document.getElementById("selected_device").style.display = "none";
    }
};


//calling this method from 'component.js'

window.onPrintLabelClick = (labelType, labelImage, zplImage) => {
    console.log('onPrintLabelClick with param');
    labelImageOnError = labelImage;
    if (ifZebraSuccess === true && ifZplImage(labelType) == true && zplImage) {
        writeToSelectedPrinter(zplImage);
    } else if(labelImage){
        printImage(labelImage);
    }
};

 
window.ifZplImage = (labelType) => {
    return labelType && labelType.toUpperCase() === 'ZPL';
};

window.writeToSelectedPrinter = (dataToWrite) => {
    if(dataToWrite) {
        selected_device.send(dataToWrite, undefined, errorCallback);
    }
};       

window.printImage = (source) => {
    function imagetoPrint(source) {
        return "<html><head><script>function step1(){\n" +
            "setTimeout('step2()', 10);}\n" +
            "function step2(){window.print();window.close()}\n" +
            "</scri" + "pt></head><body onload='step1()'>\n" +
            "<img src='" + source + "' /></body></html>";
    }
    if(source) {
        var pwa = window.open('', '', 'height=800, width=800');
        pwa.document.write("<h1>Hello World!</h1><p>Have a nice day!</p>");
//        pwa.document.write(this.imagetoPrint(source));
        pwa.document.close();
      }
};

 

if change the IP to 'self' it is working.

Source is available as mention in image. click on 'stepover' it is showing error, blocking the browser print function.

how to check 'document.write' have permission ?? this might be causing the issue (not sure)

enter image description here

any idea how to cater this issue.

Thanks.

5
  • 2
    Without the code in text format it makes harder to understand what could be missing. Could you share the code instead of screenshots? Commented Nov 16, 2021 at 15:17
  • 2
    You can't use document.write in a web component framework. By the time the script has loaded, the document is "closed" and cannot be written to. You'll need to use another method to do what you're trying to do, or perhaps just use a Visualforce page instead.
    – sfdcfox
    Commented Nov 16, 2021 at 16:39
  • 2
    To be clear, are you trying to say you've made a Lightning Component using Aura? While they are both Lightning Components, Lightning Web Components (aka LWCs) are totally separate from and are built differently from Aura Components. Commented Nov 16, 2021 at 16:58
  • Able to find answer of my question # 1 IP related, Goto setup and search for 'CSP Trusted Sites' add the 'New Trusted Site' and select either [connect-src or frame-src or img-src or style-src or font-src or media-src] and Save it. Need to refresh browser multiple times OR clear cache.
    – Developer
    Commented Nov 18, 2021 at 9:50
  • @Sohail - I would make that an answer and not a comment. Commented Nov 18, 2021 at 13:29

1 Answer 1

0

Able to find answer of my question # 1 IP related:

Go to setup and search for 'CSP Trusted Sites'.

Click 'New Trusted Site' and select either [connect-src or frame-src or img-src or style-src or font-src or media-src] and Save it.

Need to refresh browser multiple times OR clear cache.

This solution worked for me.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .