What is wrong with my JS webassemblity player? - javascript

I am trying to port a C++ program to WASM using emscripten.
The compilation process has been mastered, but so far with the presentation, which is bad ... I have
problem:
Uncaught ReferenceError: request is not defined
request.onload = function() {
Here is my script:
<script type='text/javascript'>
request.onload = function() {
var bytes = request.response;
fetch('hello.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results => {
// Do something with the results!
console.log(results);
});
};
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
preRun: [],
postRun: [],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
canvas: (function() {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: function(text) {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.last.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Module.setStatus.last.time < 30) return; // if this is a progress update, skip it if too soon
Module.setStatus.last.time = now;
Module.setStatus.last.text = text;
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.style.display = 'none';
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
// TODO: do not warn on ok events like simulating an infinite loop or exitStatus
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
};
</script>
(updated: right code) here is my source of testing site:
https://www.dropbox.com/sh/elgdplx8xmvp51g/AAC-M0oCrA0_rgWZfrRvMt8na?dl=0 look at hello.html

Unfortunately request is not a "standard variable of connection" and is not special in any way. What you probably want is window.onload which is a global event handler available on the window object.
window is a special variable and does have the onload event handler available.
Take a look at the documentation for onload
<script type='text/javascript'>
window.onload = function() {
var bytes = request.response;
fetch('hello.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results => {
// Do something with the results!
console.log(results);
});
};
// Rest of your code ...

Finally a have successfuly build the program and my script now looking just only.
<script src=./a.out.js>
I have update files on my dropbox-link to test project folder for more info. https://www.dropbox.com/sh/elgdplx8xmvp51g/AAC-M0oCrA0_rgWZfrRvMt8na?dl=0
In two words it separate script for two parts in the ending of html page
1st is
<script type='text/javascript'>
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
preRun: [],
postRun: [],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
printErr: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
if (0) { // XXX disabled for safety typeof dump == 'function') {
dump(text + '\n'); // fast, straight to the real console
} else {
console.error(text);
}
},
canvas: (function() {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: function(text) {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Date.now() < 30) return; // if this is a progress update, skip it if too soon
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.style.display = 'none';
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
// TODO: do not warn on ok events like simulating an infinite loop or exitStatus
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
};
</script>
and the second one is just
<script src=./a.out.js>
full of text you cant see on link to dropbox? its a lot of code to post here
and 3rd this is that i have copy from emscripter git repo html document that it must generate (but in my way not) and also put it to drop box link, to not to spam here.

Related

JavaScript: The image attachment is added directly from the clipboard with the key combination ctrl + v

I have a task I don't know how to start. Please tell me, if there's too much code attached or if I can get any clues from old questions. Am I missing code ony in one of the files below or both?
In the client page there's only possible to drag and drop the attachment, or click square or link and then choose any files from the computer.
Task description is this:
"Purpose and need: The image attachment is added directly from the clipboard with ctrl + v.
The server has an interface at xxxxx.com. Attachments are sent on PUT request and the query portion of the address is, for example, like ?attachment_id[/request_id/urlkey], where attachment_id is something unique and invented, request_id is the request ID number, and urlkey is the "password" associated the request. The last two are therefore either defined or not at all. The content of the transmission itself must be a multipart/form-data model.
The server then returns a JSON response and if it was a success then the okMessage field can be found in it immediately at the root. Otherwise, an error message such as errorMessages (str arr) or errors (obj → srt) will return.
There are two places on this page to send an attachment:
Make a New Job Request. See if this is visible. Here's how to check it: document.getElementById('v1r').checked. If the file was successfully uploaded to the server, it will add a tag as an extension to this table: document.getElementById ('rootNew')._fields.appendixTags.i.a_newTags.
Previously sent request. See if this is visible. Here's how: document.getElementById('v2r').checked && document.getElementById ('justRequest') parentElement.style.display != 'nothing'
(v1r and v2r are mutually exclusive, meaning only one can be visible at a time) Then, when the file has been successfully uploaded, even if you call this function, it will already be the text you want to see: l_help_addFileList(lt, name, size, mime, days) however, only name information is currently used. But where lt comes from in 1, is document.getElementById('justNew')._fields.appendixTags.i.e_sentFiles, and the conditions in section 2 are: document.getElementById('requestAttachment').e_sentFiles.
Job Request Response (Email) Not yet
In step 2, the credentials can be angled from the tag_id and tag_key data stored in the document.getElementById ('comment') element."
I have no idea where to start. I have two javascript files: index and sendAttachment. First of all, must I modify both files or only sendAttachment one?
Secondly, what I'm missing from the code so that in addition to dragging and droping , attachments can also be attached with ctrl + v?
I appreciate your help. Thank you!
Here's the current codes from client side:
index.js
//SOME CODE FIRST
//Send button
{
let send = document.createElement('div');
send.id = 'send';
send.className = 'tr';
let button = document.createElement('input');
button.type = 'button';
button.onclick = new_sendForm;
button.value = 'Submit';
send.appendChild(button);
root.appendChild(send);
root._send = button;
}
//Shows that notification is received
{
let note = document.createElement('div');
note.id = 'new_note';
note.style.display = 'none';
let div = document.createElement('div');
let text = document.createElement('h2');
text.textContent = 'Sended successfully';
div.appendChild(text);
let button = document.createElement('input');
button.type = 'button';
button.onclick = function reset(){
note.style.display = 'none';
new_resetForm();
if (root._fields.attachmentTags)
l_addBufferedAttachmentInformation(root._fields.attachmentTags.i, []);
};
button.value = 'Empty form';
div.appendChild(button);
div.appendChild(document.createElement('br'));
div.appendChild(document.createElement('br'));
let p = document.createElement('i');
p.textContent = 'You can find this and previous requests from the tab named Previous'
+ ' if you gave your email address.'
;
div.appendChild(p);
p = document.createElement('p');
p.style.fontFamily = "'Lucida Console', monospace";
p.innerHTML = 'Here's the link<br>';
let a = document.createElement('a');
a.href = '#';
a.textContent = 'The link isn't created yet';
p.appendChild(a);
div.appendChild(p);
note.appendChild(div);
root.appendChild(note);
root._note = note;
root._note_a = a;
}
{
let email = root._fields['email'];
let o = s_get();
if (email && email.i && !email.i.value && o.email)
email.i.value = o.email;
}
}
// ----------------------------------------------------------------------------
function show_comment(){
let comment = document.getElementById('comment');
let selection = null;{
let inputs = comment.getElementsByTagName('input');
for (let i=0, ii=inputs.length; i<ii; i++){
let input = inputs.item(i);
if (input.checked){
selection = input.value;
break;
}
}
}
let n_comment = document.getElementById('n_comment');
let n_comment_error = document.getElementById('n_comment_error');
let n_comment_button = document.getElementById('n_comment_button');
if (!selection)
n_comment_error.textContent = 'Not done';
else if (!n_comment.value.trim())
n_comment_error.textContent = 'Comment missing';
else {
n_comment_error.textContent = '';
n_comment_button.disabled = true;
let post = {
feature: "addComment",
getRequest: {
id: comment.key_id,
urlkey: comment.key_key,
status: selection,
description: n_comment.value
}
}
xhr(
function ok(json){
n_comment_button.disabled = false;
if (json.errorMessages)
n_comment_error.innerHTML = json.errorMessages.join('<br>');
else
n_comment.value = '';
if (json.requests && json.requests[0]){
let request = json.requests[0];
let label = document.getElementById('rootRequest').getElementsByTagName('h3').item(0);
if (label && request.jira_fields && request.jira_fields.description){
label.nextElementSibling.innerHTML = '';
doc2html(request.jira_fields.description, bella.nextElementSibling);
}
}
},
'/api',
JSON.stringify(post),
function err(json){
n_comment_button.disabled = false;
n_comment_error.textContent = 'Sending failed';
}
);
}
}
//OTHER CODES BEFORE NEXT ONES:
//Attachments part
let requestAttachment = document.getElementById('requestAttachment');
if (request.jira_fields && request.jira_fields.attachment)
l_addJiraAttachmentInfo(requestAttachment, request.jira_fields.attachment);
else if (pyynto.attachmentTags)
l_addBufferedAttachmentInfo(requestAttachment, request.attachmentTags);
else
l_addBufferedAttachmentInfo(requestAttachment, []);
} else {
root.innerHTML = 'Didn't find the request';
}
root.parentElement.style.display = 'inline-block';
}
function show_get(id, urlkey){
xhr(
function ok(json){
show_show(json);
},
'/api',
JSON.stringify({
feature: 'get',
getRequest: {
id: id,
urlkey: urlkey
}
}),
function err(json){
let root = document.getElementById('rootRequest');
root.innerHTML = '<b>Download failed</b>';
}
);
}
function show_initLomake(){
let get = getParameters();
let root = document.getElementById('rootRequest');
if (get['id'] && get['idKey']){
root.innerHTML = '<i>Searching...</i>';
show_get(get['id'], get['idKey']);
//Switching page
document.getElementById('v2r').checked = true;
} else {
root.parentElement.style.display = 'none';
}
let requestAttachment = document.getElementById('requestAttachment');
let comment = document.getElementById('comment');
if (typeof l_createForm === 'function' && requestAttachment && comment)
l_createForm(requestAttachment, comment);
else if (comment)
requestAttachment.parentElement.style.display = 'none';
}
function list_sendLink(email){
if (email){
xhr(
function ok(json){
let root = document.getElementById('rootList');
if (json.okMessage)
root.textContent = json.okMessage;
else if (json.errors && json.errors['sendMssage']){
let div = document.createElement('div');
div.textContent = json.errors['sendMessage'];
div.className = 'error';
root.appendChild(div);
} else if (json.errorMessages && json.errorMessages[0]){
let div = document.createElement('div');
div.textContent = json.errorMessages[0];
div.className = 'error';
root.appendChild(div);
} else
root.innerHTML = "Something went wrong. Don't know what or where.";
},
'/api',
JSON.stringify({
feature: 'sendListTag',
newForm: {
email: email
}
}),
function err(json){
let root = document.getElementById('rootList');
let div = document.createElement('div');
div.textContent = 'Sending the request to server failed???';
div.className = 'error';
root.appendChild(div);
}
);
}
}
function list_initShowPrevious(){
let get = getParameters();
let store = s_get();
let root = document.getElementById('rootList');
let mm_list = document.getElementById('mm_list');
let email = get['email'];
let listTag = get['list'];
if (store.email && store.listTag){
s_forgetButton(true);
if (!email || !listag || store.email == email && store.listTag == listTag){
email = store.email;
listTag = store.listTag;
mm_list.innerHTML = 'Email and list tags.';
} else {
mm_list.innerHTML = 'Email and list tag, but they differ!<br><i>If you want to update, you must forget old infos first.</i>';
}
} else if (email && listTag){
s_post(email, listTag);
mm_list.innerHTML = 'Email and list tags (saved now).';
s_forgetButton(true);
} else {
mm_list.innerHTML = 'Nothing';
}
if (email && listTag){
root.innerHTML = '<i>Searching...</i>';
list_get(email, listTag);
if (!get['form'])
document.getElementById('v2r').checked = true;
}
}
// ----------------------------------------------------------------------------
function init(){
//New form?
xhr(
function settingsGot(json){
new_initForm(json);
window._settings = json;
list_initShowPrevious();
show_initForm();
},
'form.new.json',
null,
null
);
}
sentAttachment.js
'use strict';
function l_createForm(root, settingSource){
if (!root || !ss || !ss.SimpleUpload){
console.error("Formatting of downloading attachment file failed.");
} else {
root.a_settingSource = settingSource;
root.a_newTags = [];
{
let sendedFiles = document.createElement('fieldset');
root.e_SendedFiles = sendedFiles;
sendedFiles.className = 'sendedFiles';
let legend = document.createElement('legend');
legend.innerHTML = 'Sended files';
sendedFiles.appendChild(legend);
root.appendChild(sendedFiles);
}
{
let progressBox = document.createElement('div');
root.e_progressBox = progressBox;
progressBox.className = 'progressBox';
root.appendChild(progressBox);
}
{
let key = document.createElement('p');
root.e_key = key;
key.className = 'key';
key.innerHTML = '<span>Drag and drop the files you want to send to the square above</span> ' +
'or <a>click here</a>';
root.e_clicking = key.lastElementChild;
root.appendChild(key);
}
root.e_fileUpload = new ss.SimpleUpload({
button: [root.e_sendedFiles, root.e_clicking],
url: function before(xhr, settings){
let extra = '';
if (settingSource && settingSource.tag_id && settingSource.tag_key)
extra = '/' + settingSource.tag_id + '/' + settingSource.tag_key;
return location.protocol +
'//' + location.host +
'/api?' +
(Date.now()) +
extra
;
},
name: "file",
method: "PUT",
dropzone: root,
dragClass: 'fileOn',
encodeHeaders: true,
cors: false,
multiple: true,
multipleSelect: true,
noParams: true,
multipart: true,
autoSubmit: true,
responseType: "json",
debug: false,
onDone: function sendingPassed(
fileName,//String
statusCode,//the response status code, if any
statusText,//the response status code, if any
json,//false
button,//Button which started sending
fileSize//number or null
){
let sendedFiles = root.e_sendedFiles;
if (sendedFiles){
l_help_addFileToList(
sendedFiles,
fileName,
fileSize,
null,
null
);
if (json && json.attachmentTag)
root.a_newTags.push(json.attachmentTag);
} else {
alert('File "' + fileName + '" sended successfully.');
}
},
onError: function sendingError(
fileName,//String
errorType,//"error" or "parseerror"
statusCode,//the response status code, if any
statusText,//the response status code, if any
answer,//false
button,//Button which started sending
fileSize//number or null
){
alert('"' + fileName + '": ' + statusText);
},
onSubmit: function(filename, extension) {
// Create the elements of our progress bar
var progress = document.createElement('div'), // container for progress bar
bar = document.createElement('div'), // actual progress bar
fileSize = document.createElement('div'), // container for upload file size
wrapper = document.createElement('div'), // container for this progress bar
//declare somewhere: <div id="progressBox"></div> where you want to show the progress-bar(s)
progressBox = root.e_progressBox; //on page container for progress bars
// Assign each element its corresponding class
progress.className = 'progress progress-striped';
bar.className = 'progress-bar progress-bar-success';
fileSize.className = 'size';
wrapper.className = 'wrapper';
// Assemble the progress bar and add it to the page
progress.appendChild(bar);
wrapper.innerHTML = '<div class="name">Sending <b>'+filename+'</b></div>'; // filename is passed to onSubmit()
wrapper.appendChild(fileSize);
wrapper.appendChild(progress);
progressBox.appendChild(wrapper); // just an element on the page to hold the progress bars
// Assign roles to the elements of the progress bar
this.setProgressBar(bar); // will serve as the actual progress bar
this.setFileSizeBox(fileSize); // display file size beside progress bar
this.setProgressContainer(wrapper); // designate the containing div to be removed after upload
}
});
}
}
function l_help_addFileToList(root, name, size, mime, date){
let square = document.createElement('div');
square.className = 'square';
let text = document.createElement('span');
text.className = 'name';
text.innerHTML = name;
square.appendChild(text);
/*
let size = document.createElement('i');
size.className = 'size';
size.innerHTML = size;
square.appendChild(size);
*/
root.appendChild(square);
}
function l_addJiraAttachmentInfo(root, attachment_arr){
if (root.e_sendedFiles && attachment_arr instanceof Array){
root.e_sendedFiles.innerHTML = '';
root.a_newTags = [];
for (let i=0, ii=attachment_arr.length; i<ii; i++){
let a = attachment_arr[i];
l_help_addFileToList(
root.e_sendedFiles,
a.filename,
a.size,
a.mimeType,
a.created
);
}
}
}
function l_addBufferedAttachmentInfo(root, attachmentTags){
if (root.e_sendedFiles && attachmentTags instanceof Array){
root.e_sendedFiles.innerHTML = '';
root.a_newTags = [];
for (let i=0, ii=attachmentTags.length; i<ii; i++){
let a = attachmentTags[i];
l_help_addFileToList(
root.e_sendedFiles,
'Sending_' + a,
-1,
null,
null
);
}
}
}
function l_getSendedTags(root){
if (root.a_newTags)
return root.a_newTags;
else
return null;
}

Why does this barcode detection cause Chrome or the whole Android OS to crash?

I built a barcode scanning system using Chrome's built-in BarcodeDetector. I based the work on Paul Kinlan's QR code scanner which works fine on my phone, but when I run my own code on my phone, it often causes Chrome or the whole System UI to freeze. Sometimes it gets so bad that I need to restart the phone by holding down the power button.
I have tried debugging in the Chrome developer console, but when the phone freezes, so does the developer console.
When I comment out the actual QR code detection, I can leave the page open in Chrome for 10 minutes and it just keeps running. With QR code detection running, the phone will freeze anywhere from immediately to 3 minutes later.
I put the support files (js and HTML) in a Gist - I don't think they are the issue because everything works when the barcode scanning is commented out.
My first attempt:
// Inspired by/based on on https://github.com/PaulKinlan/qrcode/blob/production/app/scripts/main.mjs
import WebCamManager from './scan/WebCamManager.js';
(function () {
'use strict';
var QRCodeCamera = function (element) {
var root = document.getElementById(element);
var cameraRoot = root.querySelector('.CameraRealtime');
var cameraManager = new WebCamManager(cameraRoot);
var cameraVideo = root.querySelector('.Camera-video');
// Offscreen canvas is supposed to help with processing speed
var cameraCanvas = new OffscreenCanvas(1,1);
var context = cameraCanvas.getContext('2d');
const detector = new BarcodeDetector({
formats: ['qr_code'],
});
cameraManager.onframeready = async function (frameData) {
cameraCanvas.width = cameraVideo.videoWidth;
cameraCanvas.height = cameraVideo.videoHeight;
context.drawImage(frameData, 0, 0, cameraVideo.videoWidth, cameraVideo.videoHeight);
if (self.onframe) {
// Comment out the line below to stop processing QR codes
await self.onframe(cameraCanvas);
}
};
var processingFrame = false;
self.onframe = async function (cameraCanvas) {
// There is a frame in the camera, what should we do with it?
if (processingFrame == false) {
processingFrame = true;
let result = await detector.detect(cameraCanvas);
processingFrame = false;
if (result === undefined || result === null || result.length === 0) {
return
};
if ('vibrate' in navigator) {
navigator.vibrate([200]);
}
cameraManager.stop();
var currentURL = new URL(window.location.href);
var newURL;
if (result[0].rawValue
&& (newURL = new URL(result[0].rawValue))
&& newURL.hostname == currentURL.hostname
&& newURL.pathname.startsWith('/pickup/qr/')
) {
window.location.href = newURL;
} else {
alert('Unsupported QR Code: ' + result[0].rawValue);
}
cameraManager.start();
}
};
};
window.addEventListener('load', function () {
var camera = new QRCodeCamera('camera');
});
})();
I also tried splitting the QR detection to a worker (worker code in Gist), but I have the same issue:
const worker = new Worker('/js/scan-worker.js');
worker.addEventListener('message', async (e) => {
if (Array.isArray(e.data)) {
var result = e.data;
if (result === undefined || result === null || result.length === 0) {
processingFrame = false;
return
};
if ('vibrate' in navigator) {
navigator.vibrate([200]);
}
var currentURL = new URL(window.location.href);
var newURL;
if (result[0].rawValue
&& (newURL = new URL(result[0].rawValue))
&& newURL.hostname == currentURL.hostname
&& newURL.pathname.startsWith('/pickup/qr/')
) {
worker.terminate();
window.location.href = newURL;
} else {
alert('Unsupported QR Code: ' + result[0].rawValue);
}
} else {
var newError = document.createElement('div');
newError.classList.add('alert', 'alert-danger');
newError.innerHTML = e.data;
errorContainer.prepend(newError);
worker.terminate();
}
processingFrame = false;
});
cameraManager.onframeready = async function (frameData) {
if (processingFrame == false) {
cameraCanvas.width = cameraVideo.videoWidth;
cameraCanvas.height = cameraVideo.videoHeight;
context.drawImage(frameData, 0, 0, cameraVideo.videoWidth, cameraVideo.videoHeight);
if (self.onframe) {
await self.onframe(cameraCanvas, context);
}
}
};
self.onframe = async function (cameraCanvas, context) {
// There is a frame in the camera, what should we do with it?
if (processingFrame == false) {
processingFrame = true;
worker.postMessage(context.getImageData(0, 0, cameraCanvas.width, cameraCanvas.height));
}
};
Not sure if this would make a difference - all the JS code is run through Laravel Mix.

f[i].insertionPoints[0].rectangles.add({geometricBounds:

i´m desperately finding a solution for my issue. I need to place a huge amount of inline graphics in InDesign with this script, but for some reason it doesn't work. I have a very poor knowledge of Javascript and my time is running out so i cannot spend much time studying JS. I'm working in InDesign CC2014 on an iMac with Yosemite.
The following error message pops-up:
error snap:
I'll be so glad if someone give me a light on this.
main();
function main() {
var name, f, file, text,
arr = [];
if(app.documents.length != 0) {
var doc = app.activeDocument;
var folder = Folder.selectDialog("Choose a folder with images");
if (folder != null) {
app.findObjectPreferences = app.changeGrepPreferences = NothingEnum.NOTHING;
app.findGrepPreferences.findWhat = "#.+?#";
f = doc.findGrep(true);
for (i = 0; i < f.length; i++) {
name = f[i].contents.replace(/#/g, "");
file = new File(folder.fsName + "/" + name);
if (file.exists) {
f[i].contents = "";
var rect = f[i].insertionPoints[0].rectangles.add({geometricBounds:[0,0, 60, 40.667 ]} );
rect.place ( file );
rect.fit ( FitOptions.FRAME_TO_CONTENT);
}
else {
arr.push("File doesn't exist '" + name + "'");
}
}
app.findObjectPreferences = app.changeGrepPreferences = NothingEnum.NOTHING;
arr.push("------------------------------------------");
text = arr.join("\r");
writeToFile(text);
}
}
else{
alert("Please open a document and try again.");
}
}
function writeToFile(text) {
var file = new File("~/Desktop/Place inline images.txt");
if (file.exists) {
file.open("e");
file.seek(0, 2);
}
else {
file.open("w");
}
file.write(text + "\r");
file.close();
}
Problem is - probably - cause script is editing found contents and refering to it in the next lines of code.
I suggest to use backward looping and move f[i].contents = "" to the line after.
Something like:
main();
function main() {
var name, f, cF, file, text,
arr = [];
if(app.documents.length != 0) {
var doc = app.activeDocument;
var folder = Folder.selectDialog("Choose a folder with images");
if (folder != null) {
app.findObjectPreferences = app.changeGrepPreferences = NothingEnum.NOTHING;
app.findGrepPreferences.findWhat = "#.+?#";
f = doc.findGrep(true);
while(cF = f.pop()) {
name = cF.contents.replace(/#/g, "");
file = new File(folder.fsName + "/" + name);
if (file.exists) {
var rect = cF.insertionPoints[0].rectangles.add({geometricBounds:[0,0, 60, 40.667 ]} );
rect.place ( file );
rect.fit ( FitOptions.FRAME_TO_CONTENT);
cF.contents = "";
}
else {
arr.push("File doesn't exist '" + name + "'");
}
}
app.findObjectPreferences = app.changeGrepPreferences = NothingEnum.NOTHING;
arr.push("------------------------------------------");
text = arr.join("\r");
writeToFile(text);
}
}
else{
alert("Please open a document and try again.");
}
}
function writeToFile(text) {
var file = new File("~/Desktop/Place inline images.txt");
if (file.exists) {
file.open("e");
file.seek(0, 2);
}
else {
file.open("w");
}
file.write(text + "\r");
file.close();
}

Javascript trim whitespace on click

I have an email form field. On click, it executes this javascript ...
$(document).on('click', '#add_delegate', function() {
RegistrationHelper.added_delegate = true;
// var button = $(event.target);
var button = $(this);
var uri = button.data('url');
if (typeof uri === 'undefined') {
return false;
}
var input = $('#email_search');
var data = {email:input.val()};
data.text().replace(/ /g,'');
var spinner = $('#delegate_add_spinner');
spinner.css({display:'inline-block'});
$.ajax({type:'POST', url: uri, data:data}).success(function(card) {
var html = $(card);
var data_id = html.attr('data-id');
var existing_elem = $('.mini_addresscard[data-id=' + data_id + ']');
if (existing_elem.length < 1) {
input.popover('hide');
// this is in a seperate timeout because IE8 is so damn stupid; it crashes if run directly
setTimeout(function () {
$('#address_cards').append(html);
var last_card = $('#address_cards div.mini_addresscard').last();
//last_card.get(0).innerHTML = card;
// html.attr("id", 'sdklfjaklsdjf');
last_card.css({display:'none'}).show('blind');
}, 10);
} else {
var background = existing_elem.css('background');
existing_elem.css({'background':'#FFFFAC'});
existing_elem.animate({
'background-color':'#EBEDF1'
}, {
complete: function() {
existing_elem.css({background:background});
}
});
// var border_color = existing_elem.css('border-color');
// existing_elem.css({'border-color':'#EFF038'});
// existing_elem.animate({'border-color':border_color});
}
}).complete(function(data) {
spinner.hide();
}).error(function(data) {
var input = $('#email_search');
input.popover("destroy");
var error = 'Please try again later'; //incase something crazy happens
if(data.status == "422"){
error = 'You cannot add yourself as a supervisor.';
}
if(data.status == "404" ){
error = 'Could not find anyone with that email address.';
}
add_popover(input, error);
input.popover('show');
});
return false;
});
My goal is to trim the whitespace before the AJAX request
So as you can see in the code above I added the line
data.text().replace(/ /g,'');
... but now it renders that button useless. In other words the button does nothing when clicked.
Since you're using jQuery, why not make use of .trim():
This:
var data = {email:input.val()};
data.text().replace(/ /g,'');
Becomes:
var data = {email:$.trim(input.val())};
The trim supposed to remove the spaces at beginning and end of the input:
var input = $('#email_search').val();
input = input.replace(/^\s+/, '').replace(/\s+$/, '');

Web workers and Canvas data

I have seen a lot of threads about web workers and <canvas> data passing, and I'm not sure if my scenario is implementable.
I want to create a small site for users to learn to code in Javascript. When users click a button, the code is run in a web worker. To help them, I have also created methods for "printing" (which basically just adds text to a <pre> element.
// get code from user and prepend helper "functions"
var userCode = editor.getValue();
var codeWithMessages = "\n\
function print(data) { postMessage(\"\"+data); } \n\
function println(data) { postMessage(\"\"+data+\'\\n\'); } \n\
function alert(data) { postMessage('ALERT'+data); } \n\
\n" + userCode;
var codeWithMessagesAndExit = codeWithMessages + "\npostMessage('exit()');";
var blob = new Blob([codeWithMessagesAndExit], {type: 'application/javascript'});
// Obtain a blob URL reference to our worker 'file'.
var blobURL = window.URL.createObjectURL(blob);
outer.worker = new Worker(blobURL);
...
// handle messages by "printing" to the run-output element, or display
// a success message when finishing
outer.worker.addEventListener('message', function (event) {
if (event.data == "exit()") {
outer.worker.terminate();
outer.worker = null;
outer.codeRunStatus = outer.CODE_RUN_SUCCESS;
outer.errorMessage = null;
outer.outputFromLatestRun = $("#run-output").text();
$("#run-output").append("<span class='code-run-success'>\nKörning klar</span>");
enableButtons();
}
else if (event.data.indexOf("ALERT") == 0) {
alert(event.data.substring(5));
}
else {
$("#run-output").append(event.data);
}
}, false);
// start the worker
outer.worker.postMessage();
Now I want to add a canvas to the page, so users could write code to draw on it.
var canvas = document.getElementById("user-canvas");
var ctx = canvas.getContext("2d");
var imgData = ctx.getImageData(0,0,canvas.width,canvas.height);
// rest same as above
outer.worker.postMessage(imgData);
I don't know how to proceed from here. Ideally the users could write something like
myCanvas.fillStyle = "rgb(200,0,0)";
myCanvas.fillRect (10, 10, 55, 50);
and then have this processed by the event listener like I did with my print() functions. Is this possible?
DOM can't be accessed from a WebWorker.
The best way I can see is to re-define this object in the webworker, and define a protocol to transmit each call to a method. But it won't work when you need other objects like images.
Worker-side :
var CanvasRenderingContext2D = function() {
this.fillStyle = "black";
this.strokeStyle = "black";
...
this.lineWidth = 1.0;
};
["fillRect", "strokeRect", "beginPath", ... "rotate", "stroke"].forEach(function(methodName) {
CanvasRenderingContext2D.prototype[methodName] = function() {
postMessage({called: methodName, args: arguments, currentObjectAttributes: this});
};
});
...
var myCanvas = new CanvasRenderingContext2D();
myCanvas.fillStyle = "rgb(200,0,0)";
myCanvas.fillRect(10, 10, 55, 50);
Main-page side :
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var worker = new Worker( ... );
worker.onMessage = function(event) {
var data = event.data;
// Refreshing context attributes
var attributes = data.currentObjectAttributes;
for(var k in attributes) {
context[k] = attributes[k];
}
// Calling method
var method = context[data.called];
method.apply(context, data.args);
};
EDIT :
I tried to integrate it with your code (not tested). To integrate it, I had to change the structure of the messages sent by the worker.
// get code from user and prepend helper "functions"
var userCode = editor.getValue();
var codeWithMessages = '\n\
function print (data) { postMessage(["print", data.toString()]); } \n\
function println(data) { postMessage(["print", data.toString() + "\\n"]); } \n\
function alert (data) { postMessage(["alert", data.toString()]); } \n\
var CanvasRenderingContext2D = function() { \n\
this.fillStyle = "black"; \n\
this.strokeStyle = "black"; \n\
/* ... */ \n\
this.lineWidth = 1.0; \n\
}; \n\
["fillRect", "strokeRect", "beginPath", /* ... */ "rotate", "stroke"].forEach(function(methodName) { \n\
CanvasRenderingContext2D.prototype[methodName] = function() { \n\
postMessage(["canvas", {called: methodName, args: Array.prototype.slice.call(arguments), currentObjectAttributes: this}]); \n\
}; \n\
});\n' + userCode;
var codeWithMessagesAndExit = codeWithMessages + "\npostMessage(['exit']);";
var blob = new Blob([codeWithMessagesAndExit], {type: 'application/javascript'});
// Obtain a blob URL reference to our worker 'file'.
var blobURL = window.URL.createObjectURL(blob);
outer.worker = new Worker(blobURL);
...
// Define your canvas ...
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
// handle messages by "printing" to the run-output element, or display
// a success message when finishing
outer.worker.addEventListener('message', function (event) {
var method = event.data[0] || null;
var data = event.data[1] || null;
if(method == "canvas") {
// Refreshing context attributes
var attributes = data.currentObjectAttributes;
for(var k in attributes) {
context[k] = attributes[k];
}
// Calling method
var method = context[data.called];
method.apply(context, data.args);
} else if(method == "exit") {
outer.worker.terminate();
outer.worker = null;
outer.codeRunStatus = outer.CODE_RUN_SUCCESS;
outer.errorMessage = null;
outer.outputFromLatestRun = $("#run-output").text();
$("#run-output").append("<span class='code-run-success'>\nKörning klar</span>");
enableButtons();
} else if(method == "alert") {
alert(data);
} else if(method == "print") {
$("#run-output").append(data);
} else {
$("#run-output").append(event.data);
}
}, false);
// start the worker
outer.worker.postMessage();

Categories

Resources