Error: Lightning Web Security: Cannot access writeln - pdf

I'm using jsPDF library in my LWC Component by uploading it to static resources to generate a pdf from html code.
I'm able to create pdf with this code
generatePDF_1 () {
try {
const doc = new jsPDF ();
doc.setTextColor (100);
doc.text ('Hello World!', 10, 10);
doc.save ('JsPDF.pdf');
} catch (error) {
alert ('Error ' + error);
}
}
but when getting error with fromhtml
generatePDF_2 () {
try {
var doc = new jsPDF ();
doc.fromHTML ('<h1>Hello World</h1>');
doc.save ('PdfHTML.pdf');
} catch (error) {
console.log ('Error Generated2 == ', error.message);
}
}
here is the error:
Error Generated2 == Lightning Web Security: Cannot access writeln.
I'm using these two library
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.3.4/jspdf.plugin.autotable.min.js">
I have checked them out & found out that there is this code in jspdf.debug.js where writeln function is used, & LWC security is not allowing to use it.
$hiddendiv = document.createElement('div');
$hiddendiv.style.cssText = visuallyhidden;
$hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
document.body.appendChild($hiddendiv);
$frame = window.frames[framename];
$frame.document.open();
$frame.document.writeln(element);
$frame.document.close();
return $frame.document.body;
I have no idea what to do now

Related

Getting Bad method 405 response while trying to upload a file to Google Cloud Storage using SAP ui5

I am trying to upload a file to Google Cloud Storage using a basic uploader in UI5.
When I am uploading the file, I am getting a 405 error in my response.
My controller code goes like this.
Please let me know if I am making any mistake anywhere.
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
return Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function() {
var oFileUploader = this.byId("fileUploader");
var prop = oFileUploader.getValue();
var path = oFileUploader.getUploadUrl();
MessageToast.show(prop);
MessageToast.show(path);
// var form = new FormData();
//form.append("files", fileInput.files[0],"C:\Users\i347520\Desktop\pan.jpg");
/*eslint-disable*/
var settings = {
"url": "https://storage.googleapis.com/upload/storage/v1/b/testocr-1234/o?uploadType=media&name=prop"
/*eslint-enable*/
};
oFileUploader.upload(settings);
}
});
});
View:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
</mvc:View>

webrtc: createAnswer works on chrome but fires an error with firefox

function createPeerConnection() {
try {
pc = new RTCPeerConnection(null, pc_constraints);
pc.onicecandidate = handleIceCandidate;
pc.onaddstream = handleRemoteStreamAdded;
pc.onremovestream = handleRemoteStreamRemoved;
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
try {
// Reliable Data Channels not yet supported in Chrome
sendChannel = pc.createDataChannel("sendDataChannel",
{reliable: false});
sendChannel.onmessage = handleMessage;
trace('Created send data channel');
} catch (e) {
alert('Failed to create data channel. ' +
'You need Chrome M25 or later with RtpDataChannel enabled');
trace('createDataChannel() failed with exception: ' + e.message);
}
sendChannel.onopen = handleSendChannelStateChange;
sendChannel.onclose = handleSendChannelStateChange;
pc.ondatachannel = gotReceiveChannel;
}
function doAnswer() {
console.log('Sending answer to peer.');
pc.createAnswer(setLocalAndSendMessage, null, sdpConstraints);
}
I got error:
TypeError: Argument 2 of mozRTCPeerConnection.createAnswer is not an object.
The following code should work in Firefox:
function doAnswer() {
console.log('Sending answer to peer.');
pc.createAnswer(setLocalAndSendMessage, handleCreateAnswerError, sdpConstraints);
}
function setLocalAndSendMessage(sessionDescription) {
sessionDescription.sdp = preferOpus(sessionDescription.sdp);
pc.setLocalDescription(sessionDescription);
console.log('setLocalAndSendMessage sending message' , sessionDescription);
sendMessage(sessionDescription);
}
function handleCreateAnswerError(error) {
console.log('createAnswer() error: ', e);
}
The reason why this fails in Firefox can be found in the documentation for createAnswer. The issue is that Firefox won't let you pass null for the error handler. All this requires is that you write your own and then pass it into createAnswer. Don't pass null, you should actually be passing a function (object) to do something with the error.
Sorry for the late response, better late than never!
how about this? Its what the guys # xsockets use...
pc.createAnswer(setLocalAndSendMessage,function (ex) { self.onerror(ex); }, sdpConstraints);

Problems with download link in phonegap android pdf

Someone know how to download an file (pdf) using phonegap for android
I already looked a lot of tutorial but any of them work for me.
THank you.
You will need to make use of the FileTransfer object here: http://docs.phonegap.com/en/3.3.0/cordova_file_file.md.html#FileTransfer.
With this, you will need to call the download method - passing in the file URI, destination and success/error callbacks.
I.e., if I want to download a PDF, you could do so as follows:
var win = function(r) {
console.log("Should not be called.");
}
var fail = function(error) {
// error.code == FileTransferError.ABORT_ERR
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var ft = new FileTransfer();
ft.download(
'http://www.mydomain.com/mypdfdoc.pdf',
myURI, // you can obtain this via a window.requestFileSystem(...)
function (fileEntry) {
// do something with fileEntry
},
function (error) {
// handle error appropriately
});

IBM Worklight 6.0 - Getting "Uncaught type error cannot call method 'initCollection' of undefined"

I'm working with Worklight to build an application which uses a local storage. I declared a function createCollection() in common/js/myApp.js.
However when I run it on the browser simulator, the console JavaScript shows:
Uncaught TypeError: Cannot call method 'initCollection' of undefined.
Any suggestions?
My JavaScript:
function wlCommonInit(){
// Common initialization code goes here
}
// inizializzazione json
window.onload = createCollection;
var isOpen = true;
var menuboxw = $("#menubox").css("width");
$("#contentbox").css("left",menuboxw);
var headerh = $("#header").height();
$("#contentbox").css("top", headerh);
$("#menu_btn").click(function(){menu()});
// apertura/chiusura menu principale
function menu() {
if(isOpen){
$('#contentbox').animate({ left: -5 }, 1);
$("#menubox").css("visibility", "hidden");
isOpen = false;
}
else{
$('#contentbox').animate({ left: menuboxw }, 1);
$("#menubox").css("visibility", "visible");
isOpen = true;
}
}
// creazione collection 'canti' e 'categorie'
function createCollection(){
WL.Logger.debug("Called createCollection");
WL.SimpleDialog.show("Message", "createCollection called", [{text: "Ok"}]);
var collectionCanti = "canti";
var searchFieldsCanti = {titolo: "string", autore: "string", id_categoria: "string", testo: "string"};
var collectionCategorie = "categorie";
var searchFieldsCategorie = {titolo: "string", attiva: "number"};
var success = function(data){
logMessage("Collection created successfully " + data);
};
var failure = function(data){
logMessage("Collection doesn't created " + data);
};
var options = {onSuccess: success, onFailure: failure};
canti = WL.JSONStore.initCollection(collectionCanti, searchFieldsCanti, options);
categorie = WL.JSONStore.initCollection(collectionCategorie, searchFieldsCategorie, options);
}
Do the following:
Remove window.onload = createCollection;
Add createCollection(); inside wlCommonInit()
BTW, that logMessage produces errors. Should probably be changed to WL.Logger.debug (which you are already utilizing in the code...).
Please go over the IBM Worklight Getting Started training material. No skipping.

Access sd card in android for uploading a file to my php server using phonegap

I want to go to select a file from sdcard and upload it to server. is it possible to access the sdcard in android via phonegap as how we are picking a image from gallery and uploading. I went through samples but all are specifying the file name also like eg: mnt/sdcard/read.txt. But i want to goto only sdcard so that user can select his own file is it possible to do.
U can easily do that its very easy
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccessUpload, fail);
function onFileSystemSuccessUpload(fileSystem) {
// get directory entry through root and access all the folders
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(successReader,fail);
}
function successReader(entries) {
var i;
for (i=0; i<entries.length; i++) {
//alert(entries[i].name);
if(entries[i].isDirectory==true)
{
var directoryReaderIn = entries[i].createReader();
directoryReaderIn.readEntries(successReader,fail);
}
if(entries[i].isFile==true)
{
entries[i].file(uploadFile, fail);
}
}
};
function uploadFile(file) {
var target=""; //the url to upload on server
var ft = new FileTransfer(),path = "file://"+ file.fullPath,name = file.name;
ft.upload(path, target, win, fail, { fileName: name });
// var ft = new FileTransfer();
//ft.upload(file.fullPath, target, win, fail, options);
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
}