Using Javascript to store Data - javascript

I've seen posts on how to add Javascript dynamically, and posts on ways to store data with Javascript, and I thought of a way to store data.
I'm trying to add a Javascript file (which contains variables/data) dynamically to a page to get Level data?
EDIT: I've done more testing, I now have an onload check, but the try{ initializeLevel } is still returning an error:
ReferenceError {stack: (...), message: "initializeLevel is not defined"}
message: "initializeLevel is not defined"
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
__proto__: Error
New Level.js
Level_State = new Object();
Level_State.LOADED = 1921;
Level_State.UNLOADED = 183;
Level_State.CURRENT = '';
function openLevel(src){
var element = document.getElementById('levelDat');
try{src.toString();}catch(e){}
src = 'Level/'+src+'.js';
element.src = src;
element.onload = parseLevel();
}
function parseLevel(){
alert('Parsing JS');
try{
initializeLevel();
generateLevel();
}catch(e){
closeLevel();
}
}
function closeLevel(){
alert('Error Loading JS FILE');
var element = document.getElementById('levelDat');
element.src = '';
}
function generateLevel(){
alert('Generating JS');
}
and Test.js contains
function initializeLevel(){
testMap = new MapDat('testMapTheSecond');
LevelData = new LevelDat('testLevel#2',testMap);
}

Related

Blazor WebbAssembly exception when calling javascript function?

I have a C# function that is invoking a Javascript function, this is the C# function:
await _jsRuntime.InvokeVoidAsync("setMediaUsingStreaming", type, dotnetImageStream);
And this is the Javascript function:
async function setMediaUsingStreaming(fileType, fileStream) {
try {
const arrayBuffer = await fileStream.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
var newHTMLElement;
var fileHTMLElement = document.getElementById('fileDisplay');
if (fileType == "image") {
newHTMLElement = document.createElement('img');
}
else {
newHTMLElement = document.createElement('video');
var attribute = document.createAttribute('controls');
newHTMLElement.setAttributeNode(attribute);
}
fileHTMLElement.appendChild(newHTMLElement);
newHTMLElement.src = url;
} catch (Exception)
{
console.log(Exception)
}
}
When the C# function is invoking the Javascript function I receive this error :
blazor.webassembly.js:1 Uncaught (in promise) Error:
Microsoft.JSInterop.JSException: Cannot set properties of null
(setting 'src') TypeError: Cannot set properties of null (setting
'src')
The weird thing is that I receive this error when I run the app in publish mode (withouth a debugger) but it works perfectly in debug mode. The catch from the javascript function is not hit when I receive this error, it seems that is the C# method that is throwing it.
I know what the error is saying, that the url variable is null, but I don't understand why is null, and why it works on debug mode.
Do you have any ideas ?

pass data response from xhr to html element

I have input element in my page, and i receive data from XMLHttpRequest when i click button.
I try to pass some data to html element, the data receive correctly but i can't pass to element.
this is my code
<input type="text" value="5" id="a" />
<script>
(function() {
let origOpen = XMLHttpRequest.prototype.open;
let a = 0;
XMLHttpRequest.prototype.open = function() {
console.log('request started!');
this.addEventListener('load', function() {
console.log('request completed!');
console.log(this.readyState); //will always be 4 (ajax is completed successfully)
console.log((JSON.parse(this.responseText)).input.a); // result = 20
a = parseInt((JSON.parse(this.responseText)).input.a);
$("#a").val(a); // not work
$("#a").setAttribute('value',a); // error: TypeError: $(...).setAttribute is not a function
document.getElementById("a").value = a; // error: TypeError: document.getElementById(...) is null
$("#a").value = a; // not work
});
origOpen.apply(this, arguments);
};
})();
</script>
The problem is in your request. Providing you really want to use the relict that XHR is it should be refactored this way:
const input = document.getElementById('a');
const myReq = new XMLHttpRequest();
myReq.onload = function() {
const data = JSON.parse(this.responseText);
input.value = data;
};
myReq.onerror = function(err) {
console.log(err);
};
myReq.open('get', '[your url]', true);
myReq.setRequestHeader('Accept', ' application/json');
myReq.send();
I have tested this code and it works with a dumb api.

How to call the expression function in different page

I am working on a cordova app and trying to record voice. I need to call expression function outside the declaration. Below is the plugin which I am using, but getting an error - Media undefined and I am unable to access Media object
cordova.define("cordova-plugin-media.Media", function(require, exports, module)
{
var Media = function(src, successCallback, errorCallback, statusCallback) {
argscheck.checkArgs('sFFF', 'Media', arguments);
this.id = utils.createUUID();
mediaObjects[this.id] = this;
this.src = src;
this.successCallback = successCallback;
this.errorCallback = errorCallback;
this.statusCallback = statusCallback;
this._duration = -1;
this._position = -1;
exec(null, this.errorCallback, "Media", "create", [this.id, this.src]);
};
Media.prototype.play = function(options) {
exec(null, null, "Media", "startPlayingAudio", [this.id, this.src, options]);
};
}
var src = "myrecording.mp3";
// Geeting error - Media undefined and I am unable to access Media object
var mediaRecorder = new Media(src,
// success callback
function () {
clearInterval(_media.intervalTimer);
console.log("recordAudio():Audio Success");
},
// error callback
function (err) {
console.log("recordAudio():Audio Error: " + err.code);
}
);

nativescript: modal property is undefined

I'm create datepicker modal select library on nativescript.
var pagesModule = require("ui/page");
var datePickerModule = require("ui/date-picker");
var moment = require('momentjs');
var frame = require('ui/frame');
module.exports.init = function(tarih, callBack) {
var dt = new datePickerModule.DatePicker();
var page = new pagesModule.Page();
page.content = dt;
page.height = 250;
var parent = frame.topmost().currentPage;
parent.modal.showModal(page, '', function() {
callBack();
});
};
I'm calling this library on main js file;
var dm = require('../../../lib/dateModal');
exports.tarihCagir = function(nesne) {
dm.init('', function() {
console.log('kapatıldı');
});
};
I'm getting this error; 'TypeError: Cannot read property 'showModal' of undefined.
This problem may be not complicated but i'm newbie for nativescript.
I'm solved problem. Changed parent.modal.showModal code to parent.showModal.

Store retrieved data from indexed DB to a variable

I am using the following code to read data from Indexed DB and save it in variable allDownloadContent
ereaderdownload.indexedDB.getAllTodoItems = function() {
/*var todos = document.getElementById("todoItems");
todos.innerHTML = "";
*/
var db = ereaderdownload.indexedDB.db;
var trans = db.transaction(["downloadcontent"], "readwrite");
var store = trans.objectStore("downloadcontent");
var request = store.get(0);
request.onsuccess = function(e) {
console.log(e.target.result);
};
// Get everything in the store;
var cursorRequest = store.openCursor();
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false)
return;
allDownloadContent.push(result);
result.continue();
};
alert("content "+allDownloadContent[0]);
cursorRequest.onerror = ereaderdownload.indexedDB.onerror;
};
When I call the getAllTodoItems method from another Javascript file I am getting a alert message content undefined
since the cursorRequest.onsuccess method executes async I am getting undefined.
I cannot make use of web workers since it is not supported in chrome.
I tried promise in Jquery. Still I am getting the same alert message.
Please help me in resolving the issue.
As for now all browsers only support the Indexed-db ASync API, and what you need to do is add an event listener to the transaction oncomplete event. This event will fire when cursor is closed. From there you can return to your code:
trans.oncomplete = function (event) {
console.log('transaction completed');
yourFunction();
};

Categories

Resources