bug:ReferenceError: self is not defined exif-js - javascript

Am getting an error while finding the exif information of an image (base64 image data):
Exif.getData(path, () => {
const tag = Exif.getTag(this, 'Orientation');
console.log(tag);
});
ReferenceError: self is not defined
/usr/local/lib/node_modules/exif-js/exif.js:931
if ((self.Image && img instanceof self.Image)
^
can anyone help

Are you executing this snippet in Client side JS or Node.js ?
Currently exif.js is developed based on the self object. It supports only client side Javascript.
Register exif.js after window load, Attached sample snippet for reference.
window.onload=getExif;
function getExif() {
var img1 = document.getElementById("img1");
EXIF.getData(img1, function() {
var make = EXIF.getTag(this, "Make");
var model = EXIF.getTag(this, "Model");
var makeAndModel = document.getElementById("makeAndModel");
makeAndModel.innerHTML = `${make} ${model}`;
});
var img2 = document.getElementById("img2");
EXIF.getData(img2, function() {
var allMetaData = EXIF.getAllTags(this);
var allMetaDataSpan = document.getElementById("allMetaDataSpan");
allMetaDataSpan.innerHTML = JSON.stringify(allMetaData, null, "\t");
});
}

Exif parser works perfectly in server side.
https://www.npmjs.com/package/exif-parser

Related

& to & in base64 + Javascript

I've got a new problem within my project. I want to create a pdf file via pdfmake. I was following this tutorial and everything works fine, except the "transformation" of the '&' sign. In my 'var docDefinition' I am getting content from mysql database. There are some enterprise names with '&'-sign in it. If I call the enterprise name within php, the '&'-sign is shown correctly. But within the javascript and through convert to base64, only 'ampersand' is shown in the generated pdf.
Other signs like 'ö', 'ä' etc. are shown correctly.
Any ideas?
### Update
Here is a snippet of my code 'generatePDF.blade.php':
#section('scripts')
<script type="text/javascript">
...
// Create the PDF
var docDefinition = {
pageSize: 'A4',
pageOrientation: 'portrait',
...
content: [
{ text: 'Ausführende Firma: '},
'{{ $report->user->enterprise->enterprise_name }}',
...
],
};
And then the stuff from the tutorial:
//save the pdf into base64 strings
var pdfstr;
try {
pdfMake.createPdf(docDefinition).getDataUrl(function (result) {
pdfstr = result;
console.log('Result: ' + pdfstr);
var pdfAsArray = convertDataURIToBinary(pdfstr);
console.log('Array: ' + pdfAsArray);
PDFJS.getDocument(pdfAsArray).then(function getPdf(pdf) {
console.log('pdf var: ' + pdf.getPage(1));
//
// Fetch the first page
//
pdf.getPage(1).then(function getPdfPage(page) {
var scale = 1;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var canvas = $("#pdfviewer").get(0);
var context = canvas.getContext('2d');
// Check device pixel ratio and then if the browser is doubleing them
console.log('Pixelratio is', window.devicePixelRatio);
console.log('The browser is doubleing the pixels:', context.webkitBackingStorePixelRatio);
var factor = 1;
if (window.devicePixelRatio >= 2 && context.webkitBackingStorePixelRatio < 2 || context.webkitBackingStorePixelRatio == undefined) {
factor = 2;
}
//canvas.height = viewport.height*factor;
//canvas.width = viewport.width*factor;
canvas.setAttribute('width', viewport.width*factor);
canvas.setAttribute('height', viewport.height*factor);
// context.scale(factor, factor);
context.transform(devicePixelRatio,0,0,devicePixelRatio,0,0);
//
// Render PDF page into canvas context
//
var renderContext = {
canvasContext: context,
viewport: viewport,
};
page.render(renderContext);
// $('#containerPDFViewer').modal({ backdrop: 'static' }); //disable backdrop so user need to make choice
});
});
});
}
catch (e) {
throw e;
}
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
// array[i] = raw.codePointAt(i);
}
return array;
}
### Update 2
I figured out, that my problem has noting to do with the javascript part but with the laravel framework I am working with. I am sorry for not telling you, I just forgot to.
So when I am getting my data from mySQL in my blade view (both UTF-8), everything is fine. But if I do the same not within the pure blade but into javascript my error occurs. So I checked via dd($myvar->value); and so I can see, that the '$'-sign is not converted but the "ampersand ($amp;)". How can I solve that blade prob?
Okay, now I found an answer for my problem:
some tables in DB were in collation of utf8_general_ci, but in laravel /app/config/database.php there is 'collation' => 'utf8mb4_unicode_ci'. So the solution is to change the tables into that collation and then call the values from DB in blade via {!! $myvar->field !!} and woooosh, everything works as it should!

Get value of remote JS var with Jurassic Script Engine

My remote js file as below
(function(window,document){
var config = {
'placeHolder' : 'content_div'
};
var html = "blaaa blaaa";
})(window,document);
I would likte to get value of html.
I have tried as below but I have got error.
string _JsVars = this._HttpWebRequestRemoteUrl(#"http://www.remotewebpage.com");
var engine = new Jurassic.ScriptEngine();
var result = engine.(_JsVars);
var var1 = engine.GetGlobalValue<string>("html");
MessageBox.Show(var1.ToString());

Error while opening indexeddb with higher version than existing

var database = e.target.result;
var version = Number(database.version);
console.log("in onsuccess>>>>>>>>>>>>>>>>>>>>>>>>>> : "+dbName);
console.log(e);
database.close();
var secondRequest = indexedDB.open(dbName, (version+1));
console.log(secondRequest); // <-- error on this line
//console.log(secondRequest.result);
secondRequest.onupgradeneeded = function (e) {
console.log("in onupgradeneeded>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log(e);
var database = e.target.result;
//database.setVersion(12);
var objectStore = database.createObjectStore(storeName, {
keyPath: 'id'
});
};
secondRequest.onsuccess = function (e) {
console.log("000000000000000000000000000000");
e.target.result.close();
};
secondRequest.onerror = function(e){
console.log("Error ------------------- ");
console.log(e);
}
in above console I am getting following error in
console.log(secondRequest);
error:
IDBOpenDBRequest
error : [Exception: DOMException]
I have added listner
IDBOpenDBRequest.onerror = function(e){
}
But It is not going there. Help me if anybody have solution.
Although you have some of the core concepts down, your code is really hard to follow as is. To begin with, this e event assignment is undefined:
var database = e.target.result;
Where is the database open()? Where is dbName coming from?
Provide more of your failing code, preferably via jsfiddle, and we'll help you find a solution.
UPDATE: Here's a working example of what you're trying to do.
Output div:
<div id="idb_version"></div>
Code:
var db_name = 'myname',
database_open_request = window.indexedDB.open(db_name);
database_open_request.addEventListener('success', function (e) {
database = e.target.result;
database.close();
var second_database_open_request = window.indexedDB.open(db_name, database.version + 1);
second_database_open_request.addEventListener('upgradeneeded', function (e) {
database = e.target.result;
database.close();
window.document.getElementById("idb_version").innerHTML = database.version;
});
});
When not specifying a version param, you get a reference to the most recent version on success callback. Then I listen for a versionchange and increase the version by one. Run this over and over and you'll see the version increase one by one.

how to open a local PDF in PDFJS using file input?

I would like to know if there is a way to select a pdf file using input type="file" and open it using PDFJS
You should be able to use a FileReader to get the contents of a file object as a typed array, which pdfjs accepts (https://mozilla.github.io/pdf.js/examples/)
//Step 1: Get the file from the input element
inputElement.onchange = function(event) {
var file = event.target.files[0];
//Step 2: Read the file using file reader
var fileReader = new FileReader();
fileReader.onload = function() {
//Step 4:turn array buffer into typed array
var typedarray = new Uint8Array(this.result);
//Step 5:pdfjs should be able to read this
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
// The document is loaded here...
});
};
//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
}
Edit: The pdfjs API changed at some point since I wrote this first answer in 2015. Updating to reflect the new API as of 2021(thanks to #Chiel) for the updated answer
If getDocument().then is not a function:
I reckon I have managed to solve the new problem with the new API. As mentioned in this GitHub issue, the getDocument function now has an promise added to itself.
In short, this:
PDFJS.getDocument(typedarray).then(function(pdf) {
// The document is loaded here...
});
became this:
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
// The document is loaded here...
});
Adapting the older answer to the new api to comply to the bounty gives the following result:
//Step 1: Get the file from the input element
inputElement.onchange = function(event) {
//It is important that you use the file and not the filepath (The file path won't work because of security issues)
var file = event.target.files[0];
var fileReader = new FileReader();
fileReader.onload = function() {
var typedarray = new Uint8Array(this.result);
//replaced the old function with the new api
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
// The document is loaded here...
});
};
//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
}
I have created an example below with the official releases of the source code below to show that it is working.
/*Offical release of the pdfjs worker*/
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.5.207/pdf.worker.js';
document.getElementById('file').onchange = function(event) {
var file = event.target.files[0];
var fileReader = new FileReader();
fileReader.onload = function() {
var typedarray = new Uint8Array(this.result);
console.log(typedarray);
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
// The document is loaded here...
//This below is just for demonstration purposes showing that it works with the moderen api
pdf.getPage(1).then(function(page) {
console.log('Page loaded');
var scale = 1.5;
var viewport = page.getViewport({
scale: scale
});
var canvas = document.getElementById('pdfCanvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function() {
console.log('Page rendered');
});
});
//end of example code
});
}
fileReader.readAsArrayBuffer(file);
}
<html>
<head>
<!-- The offical release-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.5.207/pdf.js"> </script>
</head>
<body>
<input type="file" id="file">
<h2>Rendered pdf:</h2>
<canvas id="pdfCanvas" width="300" height="300"></canvas>
</body>
</html>
Hope this helps! If not, please comment.
Note:
This might not work in jsFiddle.
I adopted your code and it worked! Then I was browsing for more tips here and there, then I learned there is an even more convenient method.
You can get the URL of client-loaded file with
URL.createObjectURL()
It reduces nesting by one level and you don't need to read the file, convert it to array, etc.

mocha import external script failed

I have this opcode.js file and need to test it with mocha.An example can be seen here :
var opcode = {
'0': {
decode: function (data) {
var ocBuf = new OpcodeBuffer(data);
var kpo = {};
kpo.opcode = 0x00;
ocBuf.setIndex(1);
kpo.sid = ocBuf.readUInt16();
return kpo;
},
encode: function (kpo) {
var ocBuf = new OpcodeBuffer(opcode['0'].encodeLength(kpo));
ocBuf.writeUInt8(0x00);
ocBuf.writeUInt16(kpo.sid);
return ocBuf.buf;
}
module.exports = opcode;
and the write in my test_ack.js file:
var op = require('./ack.js');
var assert = require('assert');
opcode = op.opcode;
var decode = require('opcode').decode();
var encode = require('opcode').encode();
the problem is that i keep having this encode and decode not defined error messages.I still cannot get how can i import them in my directory.
Given the code you show us, this would be the way you could import your two functions:
var decode = require('opcode')["0"].decode;
var encode = require('opcode')["0"].encode;
I'd suggest additionally avoiding calling require twice. Among other things, the code you currently have calls the functions instead of just importing them.

Categories