Error accessing "autoAllocateChunkSize" in PDFJS - javascript

i have a new problem after firefox 99 update.
I have an extension that reads pdfs using PDFJS (version pdfjs-2.13.216). It always worked and after the last update it started to give: Error: Permission denied to access property "autoAllocateChunkSize"
The same extension, with tiny changes, works in chrome normally.
Below is the code:
function getAllTextPDF(urlPDF) {
return new Promise(function (resolve , reject ) {
var pdfjsLib = this['pdfjs-dist/build/pdf']; //this because of firefox
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
var loadingTask = pdfjsLib.getDocument(urlPDF);
//** from that line it no longer enters and generates the mentioned error **
loadingTask.promise.then(function(pdf) {
var numPages = pdf._pdfInfo.numPages;
var textoFinal = '';
var pagesPromises = [];
for (var i = 0; i < numPages; i++) {
(function (pageNumber) {
pagesPromises.push(getPageText(pageNumber, pdf));
})(i + 1);
}
Promise.all(pagesPromises).then(function (pagesText) {
for (var i = 0; i < pagesText.length; i++) {
textoFinal += pagesText[i];
}
if(textoFinal.length > 0){
resolve({text: textoFinal});
loadingTask.destroy();
delete pdfjsLib;
delete loadingTask;
}
});
}, function (reason) {
// PDF loading error
reject({reason});
return 0;
});
});
}
example URL of file to read (worked normally):
blob:https://dominio.com/4db038e1-ae8d-4a15-a78f-0d9d0a182c7c
The idea of ​​the method is simple, go through the pdf file and return all the text. However now as mentioned the error is generated. Detail that did not generate the error in version 32bit firefox, I believe it started in the last update of firefox 99.
I appreciate your help.

Related

Unable to update google sheet value of a cell using google spreadsheet api v4.0

I am unable to update the sheets row value of a particular cells. I am using google api v4.0 and google spreadsheet npm package. I am getting an error using it in discord bot js. The error is
(node:5956) UnhandledPromiseRejectionWarning: TypeError: rows2[i].save
is not a function
at checkStatus (D:\discortbot\src\bot.js:95:30)
My code is as follows:
sheet3 = doc2.sheetsByIndex[sheetIndex]; // Data from back which I have checked is coming correctly!
var rows2 = await sheet3.getRows({
});
rows2 = rows2.map(a=>a._rawData);
var size = rows2.length;
for(var i=0;i<size;i++){
if(rows2[i][0]==email){
rows2[i].candidateID = userID;
rows2[i].RoleID = sheetarr[2];
//rows2[i].save(); This one is also not working
console.log(rows2[i].candidateID); // Values are printing in console
console.log(rows2[i].RoleID); // Values are printing in console
await rows2[i].save(); // Error giving me
verified = 1;
break;
}
}
if(verified==1){
message.author.send("Your account has been verified.Welcome to Outscal batch!");
}else{
}
I am not able to understand why I am getting this error? Kindly help me in solving this.
How about the following modification?
Modified script:
Before you use this script, please confirm the variables you want to use, again.
var sheet3 = doc2.sheetsByIndex[sheetIndex];
var rows2 = await sheet3.getRows();
// rows2 = rows2.map(a=>a._rawData); // Removed
var size = rows2.length;
for (var i = 0; i < size; i++) {
if (rows2[i]._rawData[0] == email) { // Modified
rows2[i].candidateID = userID;
rows2[i].RoleID = sheetarr[2];
console.log(rows2[i].candidateID); // Values are printing in console
console.log(rows2[i].RoleID); // Values are printing in console
await rows2[i].save();
verified = 1;
break;
}
}
if (verified == 1) {
message.author.send("Your account has been verified.Welcome to Outscal batch!");
} else {
}
Reference:
node-google-spreadsheet

execCommand('copy') not working programatically, only when executed via DevTools console

Source:
const package = document.querySelector('td[data-bind="text: packageName"');
if (package.textContent.indexOf('Adaptive') !== -1) {
package.click();
const stacks_tab = document.querySelector('ul[class="tabsExpanded"]').children[5];
stacks_tab.click();
function get_sources() {
const sources = [];
const stacks = document.querySelectorAll('span[data-bind="text:duration"]');
for (let i = 0; i < stacks.length; i++) {
stacks[i].click();
let renditions = document.querySelectorAll('span[class="blockUnSelected"]');
renditions[(i+1) * 8 - 1].click();
sources.push(document.querySelectorAll('p[data-bind="text: $data.name"]')[0].textContent);
}
let copy = '';
for (let i = 0; i < sources.length; i++) {
const change_brackets = sources[i].replace(/\/tveorigin\/vod\/ae\//, '');
const no_pd1 = change_brackets.replace(/-pd1/g, '');
copy += no_pd1 + ',';
}
if (copy === '') {
setTimeout(get_sources, 500);
} else {
const hidden = document.createElement('input');
hidden.value = copy;
document.querySelector('body').appendChild(hidden);
hidden.select();
function copy_sources() {
console.log('running');
hidden.select();
if (!document.execCommand('copy')) {
setTimeout(copy_sources, 500);
} else {
console.log('Sources copied!');
}
}
copy_sources();
}
}
get_sources();
} else {
console.log('There is no Adaptive package in this content.');
}
Line 45 is what isn't working.
That code won't make a lot of sense, but here's the use case:
I'm trying to automate part of my job by injecting some JavaScript into the Chrome DevTools console on our CMS that we use for video content where I work. What the script does is click a few elements, then grabs some file locations and copies them to the clipboard as comma separated values. I had this working just fine before, but I decided to try and make the script better...and now the document.execCommand('copy') is just not working.
As you can see, I use some recursion to continuously select the hidden input value and then I try to copy it, and if it fails, I try again in 500 ms. I also log 'running' to ensure the function is actually running (it is). The execCommand() function keeps returning false every 500ms. BUT, if I type it into the console manually and run it, it returns true and works fine even as the recursive function continues to return false. So for some reason, it won't work in the context of my script, but works totally fine when run manually.
Like I said before, it WAS working programatically before, but I changed some stuff to make the script better and more automated, and it won't work anymore. Here's the code with execCommand() working fine:
const sources = [];
const stacks = document.querySelectorAll('span[data-bind="text:duration"]');
for (let i = 0; i < stacks.length; i++) {
stacks[i].click();
let renditions = document.querySelectorAll('span[class="blockUnSelected"]');
renditions[(i+1) * 8 - 1].click();
sources.push(document.querySelectorAll('p[data-bind="text: $data.name"]')[0].textContent);
}
let copy = '';
for (let i = 0; i < sources.length; i++) {
const change_brackets = sources[i].replace(/\/tveorigin\/vod\/ae\//, '');
const no_pd1 = change_brackets.replace(/-pd1/g, '');
copy += no_pd1 + ',';
}
const hidden = document.createElement('input');
hidden.value = copy;
document.querySelector('body').appendChild(hidden);
hidden.select();
document.execCommand('copy');
I just tested that code and it still works, and copies the text to the clipboard as intended. The only notable different I see is that in the older code, I run execCommand() in the global context, whereas in the new script, it's in a function context. Could this have something to do with it?
So the solution to this was odd. execCommand() can only be triggered by a user event handler, so what I had to do was attach a click listener to the window, then invoke a click event on the hidden node. Because that triggered a click handler, that made it work!

Using FileReader.readAsArrayBuffer() on changed files in Firefox

I'm running into an odd problem using FileReader.readAsArrayBuffer that only seems to affect Firefox (I tested in the current version - v40). I can't tell if I'm just doing something wrong or if this is a Firefox bug.
I have some JavaScript that uses readAsArrayBuffer to read a file specified in an <input> field. Under normal circumstances, everything works correctly. However, if the user modifies the file after selecting it in the <input> field, readAsArrayBuffer can get very confused.
The ArrayBuffer I get back from readAsArrayBuffer always has the length that the file was originally. If the user changes the file to make it larger, I don't get any of the bytes after the original size. If the user changes the file to make it smaller, the buffer is still the same size and the 'excess' in the buffer is filled with character codes 90 (capital letter 'Z' if viewed as a string).
Since this code is so simple and works perfectly in every other browser I tested, I'm thinking it's a Firefox issue. I've reported it as a bug to Firefox but I want to make sure this isn't just something obvious I'm doing wrong.
The behavior can be reproduced by the following code snippet. All you have to do is:
Browse for a text file that has 10 characters in it (10 is not a magic number - I'm just using it as an example)
Observe that the result is an array of 10 items representing the character codes of each item
While this is still running, delete 5 characters from the file and save
Observe that the result is still an array of 10 items - the first 5 are correct but the last 5 are all 90 (capital letter Z)
Now added 10 characters (so the file is now 15 characters long)
Observe that the result is still an array of 10 items - the last 5 are not returned
function ReadFile() {
var input = document.getElementsByTagName("input")[0];
var output = document.getElementsByTagName("textarea")[0];
if (input.files.length === 0) {
output.value = 'No file selected';
window.setTimeout(ReadFile, 1000);
return;
}
var fr = new FileReader();
fr.onload = function() {
var data = fr.result;
var array = new Int8Array(data);
output.value = JSON.stringify(array, null, ' ');
window.setTimeout(ReadFile, 1000);
};
fr.readAsArrayBuffer(input.files[0]);
//These two methods work correctly
//fr.readAsText(input.files[0]);
//fr.readAsBinaryString(input.files[0]);
}
ReadFile();
<input type="file" />
<br/>
<textarea cols="80" rows="10"></textarea>
In case the snippet does not work, the sample code is also available as a JSFiddle here: https://jsfiddle.net/Lv5y9m2u/
Interesting, looks like Firefox is caching the buffer size even the file is modified.
You can refer to this link, replaced readAsArrayBuffer with is custom functionality which uses readAsBinaryString. Its working fine in Firefox and Chrome
function ReadFile() {
var input = document.getElementsByTagName("input")[0];
var output = document.getElementsByTagName("textarea")[0];
if (input.files.length === 0) {
output.value = 'No file selected';
window.setTimeout(ReadFile, 1000);
return;
}
var fr = new FileReader();
fr.onload = function () {
var data = fr.result;
var array = new Int8Array(data);
output.value = JSON.stringify(array, null, ' ');
window.setTimeout(ReadFile, 1000);
};
fr.readAsArrayBuffer(input.files[0]);
//These two methods work correctly
//fr.readAsText(input.files[0]);
//fr.readAsBinaryString(input.files[0]);
}
if (FileReader.prototype.readAsArrayBuffer && FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsArrayBuffer = function readAsArrayBuffer () {
this.readAsBinaryString.apply(this, arguments);
this.__defineGetter__('resultString', this.__lookupGetter__('result'));
this.__defineGetter__('result', function () {
var string = this.resultString;
var result = new Uint8Array(string.length);
for (var i = 0; i < string.length; i++) {
result[i] = string.charCodeAt(i);
}
return result.buffer;
});
};
}
ReadFile();
I think you are hitting a bug of Firefox. However, as you pointed out, readAsArrayBuffer behaves correctly in every supported browser except Firefox while readAsBinaryString is supported by every browser except IE.
Therefore, it is possible to prefer readAsBinaryString when it exists and fail back to readAsArrayBuffer otherwise.
function readFileAsArrayBuffer(file, success, error) {
var fr = new FileReader();
fr.addEventListener('error', error, false);
if (fr.readAsBinaryString) {
fr.addEventListener('load', function () {
var string = this.resultString != null ? this.resultString : this.result;
var result = new Uint8Array(string.length);
for (var i = 0; i < string.length; i++) {
result[i] = string.charCodeAt(i);
}
success(result.buffer);
}, false);
return fr.readAsBinaryString(file);
} else {
fr.addEventListener('load', function () {
success(this.result);
}, false);
return fr.readAsArrayBuffer(file);
}
}
Usage:
readFileAsArrayBuffer(input.files[0], function(data) {
var array = new Int8Array(data);
output.value = JSON.stringify(array, null, ' ');
window.setTimeout(ReadFile, 1000);
}, function (e) {
console.error(e);
});
Working fiddle: https://jsfiddle.net/Lv5y9m2u/6/
Browser Support:
Firefox: Uses readAsBinaryString, which is not problematic.
IE >= 10: Uses readAsArrayBuffer which is supported.
IE <= 9: The entire FileReader API is not supported.
Almost all other browsers: Uses readAsBinaryString.

Chrome and Firefox incompatibility

I have two frames, the expression running in first frame and calling highlightElements function in another frame. This expression works fine in Firefox:
parent.frames[0].highlightElements(lineNumbers, stringObj);
The highlightElements function (just for sure):
function highlightElements(lineNumbers, stringObj) {
// run through the cycle and highlight them
//for (var ln in lineNumbers) {
var length = lineNumbers.length;
for (var ln=0; ln<length; ln++) {
var elements = $('.no');
//for (var i in elements) {
var el_length = elements.length;
for (var i=0; i<el_length; i++) {
if (parseInt(elements[i].innerHTML) == lineNumbers[ln]) {
var badThing = "yes";
for (var nextElement = elements[i].next();
nextElement.className != '.no'; nextElement = elements[i].next()) {
if (nextElement.innerHTML == stringObj) {
badThing = "no";
nextElement.effect('highlight', {}, 'slow');
scrollIntoView(nextElement);
}
}
if (badThing == "yes") alert("Didn't find the object");
}
}
}
}
But in Chrome it produces the error "Uncaught TypeError: Property 'highlightElement' of object[objectDOMWindow] is not a function".
How to change the expression to make it runnable in Chrome? Thanks
Make sure both frames are under same domain and protocol. Chome blocks javascript access from frames to another if the domains/protocols don't match. If you are working locally, and not under a local domain (i.e. the url is something like file:///C:/etc/etc.html) then it won't work either.

Print function log /stack trace for entire program using firebug

Firebug has the ability to log calls to a particular function name. I'm looking for a bug that sometimes stops a page from rendering, but doesn't cause any errors or warnings. The bug only appears about half the time. So how do I get a list of all the function calls for the entire program, or some kind of stack trace for the execution of the entire program?
Firefox provides console.trace() which is very handy to print the call stack. It is also available in Chrome and IE 11.
Alternatively try something like this:
function print_call_stack() {
var stack = new Error().stack;
console.log("PRINTING CALL STACK");
console.log( stack );
}
When i need a stack trace i do the following, maybe you can draw some inspiration from it:
function logStackTrace(levels) {
var callstack = [];
var isCallstackPopulated = false;
try {
i.dont.exist += 0; //doesn't exist- that's the point
} catch (e) {
if (e.stack) { //Firefox / chrome
var lines = e.stack.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
callstack.push(lines[i]);
}
//Remove call to logStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
else if (window.opera && e.message) { //Opera
var lines = e.message.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
var entry = lines[i];
//Append next line also since it has the file info
if (lines[i + 1]) {
entry += " at " + lines[i + 1];
i++;
}
callstack.push(entry);
}
}
//Remove call to logStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
}
if (!isCallstackPopulated) { //IE and Safari
var currentFunction = arguments.callee.caller;
while (currentFunction) {
var fn = currentFunction.toString();
var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || "anonymous";
callstack.push(fname);
currentFunction = currentFunction.caller;
}
}
if (levels) {
console.log(callstack.slice(0, levels).join('\n'));
}
else {
console.log(callstack.join('\n'));
}
};
Moderator's note: The code in this answer seems to also appear in this post from Eric Wenderlin's blog. The author of this answer claims it as his own code, though, written prior to the blog post linked here. Just for purposes of good-faith, I've added the link to the post and this note.
I accomplished this without firebug. Tested in both chrome and firefox:
console.error("I'm debugging this code.");
Once your program prints that to the console, you can click the little arrow to it to expand the call stack.
Try stepping through your code one line or one function at a time to determine where it stops working correctly. Or make some reasonable guesses and scatter logging statements through your code.
Try this:
console.trace()
I don't know if it's supported on all browsers, so I would check if it exists first.

Categories

Resources