I have a website developed in C# MVC5 .NET and I need to use de MediaInfolib DLL javascript version. I am not able to load the .wasm file.
This is my .cshtml code:
<script type="text/javascript">
// Load the WebAssembly MediaInfo module if the browser supports it,
// otherwise load the asmjs module
var wasm_path ="#Url.Content("~/")" + "lib/MediaInfo_DLL/";
var MediaInfoJs = document.createElement('script');
if ('WebAssembly' in window) {
MediaInfoJs.src = wasm_path + "MediaInfoWasm.js";
} else {
MediaInfoJs.src = wasm_path + "MediaInfo.js";
}
document.body.appendChild(MediaInfoJs);
// Continue initialization
MediaInfoJs.onload = function () {
var MediaInfoModule, MI, processing = false, CHUNK_SIZE = 1024 * 1024;
var finish = function() {
MI.Close();
MI.delete();
processing = false;
}
...
MediaInfoModule = MediaInfoLib(
{'locateFile': function(path, prefix) {return wasm_path + path; }},
{ 'postRun': function () {
console.debug('MediaInfo ready');
// Information about MediaInfo
document.getElementById('result').innerText = 'Info_Parameters:\n';
document.getElementById('result').innerText += MediaInfoModule.MediaInfo.Option_Static('Info_Parameters') + '\n\n';
document.getElementById('result').innerText += 'Info_Codecs:\n';
document.getElementById('result').innerText += MediaInfoModule.MediaInfo.Option_Static('Info_Codecs') + '\n';
// Get selected file
var input = document.getElementById('input');
input.onchange = function() {
if(input.files.length > 0) {
document.getElementById('result').innerText = "Processing...";
parseFile(input.files[0], showResult);
}
}
}
});
};
</script>
I have these warnings in the MediaInfoWasm.js and the page doesn`t work:
MediaInfoWasm.js:19 failed to asynchronously prepare wasm: failed to
load wasm binary file at '/lib/MediaInfo_DLL/MediaInfoWasm.wasm'
Module.c.printErr.c.printErr # MediaInfoWasm.js:19 MediaInfoWasm.js:19
failed to load wasm binary file at
'/lib/MediaInfo_DLL/MediaInfoWasm.wasm' Module.c.printErr.c.printErr #
MediaInfoWasm.js:19
Has somebody used this MediaInfolib javascript version with MVC5?
Thanks in advance.
María José.
Related
I am developing a wpf application by using Xilium.CefGlue and Xilium.CefGlue.WPF. My WPF application is getting crashed after implementing Xilium.CefGlue.CefApp.GetRenderProcessHandler() in SampleCefApp. Before this implementation the application was working fine without any crashes. Actually I need to call a C# function from html local page by javascript function. This functionality is working fine in 32 bit version but not in 64 bit. The following is my implementation.
internal sealed class SampleCefApp : CefApp
{
public SampleCefApp()
{
}
private CefRenderProcessHandler renderProcessHandler = new Views.DemoRenderProcessHandler();
protected override CefRenderProcessHandler GetRenderProcessHandler()
{
return renderProcessHandler;
}
}
the following message was showing for app crash
<ProblemSignatures>
<EventType>APPCRASH</EventType>
<Parameter0>StreetMap.vshost.exe</Parameter0>
<Parameter1>14.0.23107.0</Parameter1>
<Parameter2>559b788a</Parameter2>
<Parameter3>libcef.DLL</Parameter3>
<Parameter4>3.2743.1449.0</Parameter4>
<Parameter5>57bbfe66</Parameter5>
<Parameter6>80000003</Parameter6>
<Parameter7>0000000000b68267</Parameter7>
</ProblemSignatures>
Is ther any issues for libcef dll while working with 64 bit. Is anybody can help for implementing JS to C# call by using Xilium.CefGlue and Xilium.CefGlue.WPF.
The following reference code i am using for this from the link
https://groups.google.com/forum/#!topic/cefglue/EhskGZ9OndY
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System;
namespace Xilium.CefGlue.Client {
internal sealed class DemoApp: CefApp {
private CefRenderProcessHandler renderProcessHandler = new DemoRenderProcessHandler();
protected override CefRenderProcessHandler GetRenderProcessHandler() {
return renderProcessHandler;
}
}
internal class DemoRenderProcessHandler: CefRenderProcessHandler {
MyCustomCefV8Handler myCefV8Handler = new MyCustomCefV8Handler();
protected override void OnWebKitInitialized() {
base.OnWebKitInitialized();
var nativeFunction = # "nativeImplementation = function(onSuccess) {
native
function MyNativeFunction(onSuccess);
return MyNativeFunction(onSuccess);
};
";
CefRuntime.RegisterExtension("myExtension", nativeFunction, myCefV8Handler);
}
internal class MyCustomCefV8Handler: CefV8Handler {
protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue,
out string exception) {
//Debugger.Launch();
var context = CefV8Context.GetCurrentContext();
var taskRunner = CefTaskRunner.GetForCurrentThread();
var callback = arguments[0];
new Thread(() => {
//Sleep a bit: to test whether the app remains responsive
Thread.Sleep(3000);
taskRunner.PostTask(new CefCallbackTask(context, callback));
}).Start();
returnValue = CefV8Value.CreateBool(true);
exception = null;
return true;
}
}
internal class CefCallbackTask: CefTask {
private readonly CefV8Context context;
private readonly CefV8Value callback;
public CefCallbackTask(CefV8Context context, CefV8Value callback) {
this.context = context;
this.callback = callback;
}
protected override void Execute() {
var callbackArguments = CreateCallbackArguments();
callback.ExecuteFunctionWithContext(context, null, callbackArguments);
}
private CefV8Value[] CreateCallbackArguments() {
var imageInBase64EncodedString = LoadImage(# "C:\hamb.jpg");
context.Enter();
var imageV8String = CefV8Value.CreateString(imageInBase64EncodedString);
var featureV8Object = CefV8Value.CreateObject(null);
var listOfFeaturesV8Array = CefV8Value.CreateArray(1);
featureV8Object.SetValue("name", CefV8Value.CreateString("V8"), CefV8PropertyAttribute.None);
featureV8Object.SetValue("isEnabled", CefV8Value.CreateInt(0), CefV8PropertyAttribute.None);
featureV8Object.SetValue("isFromJSCode", CefV8Value.CreateBool(false), CefV8PropertyAttribute.None);
listOfFeaturesV8Array.SetValue(0, featureV8Object);
context.Exit();
return new [] {
listOfFeaturesV8Array,
imageV8String
};
}
private string LoadImage(string fileName) {
using(var memoryStream = new MemoryStream()) {
var image = Bitmap.FromFile(fileName);
image.Save(memoryStream, ImageFormat.Png);
byte[] imageBytes = memoryStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
}
}
The HTML file, that I loaded at the first place:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>C# and JS experiments</title>
<script src="index.js"></script>
</head>
<body>
<h1>C# and JS are best friends</h1>
<div id="features"></div>
<div id="image"></div>
</body>
</html>
The JavaScript code:
function Browser() {
}
Browser.prototype.ListAllFeatures = function(onSuccess) {
return nativeImplementation(onSuccess);
}
function App(browser) {
this.browser = browser;
}
App.prototype.Run = function() {
var beforeRun = new Date().getTime();
this.browser.ListAllFeatures(function(features, imageInBase64EncodedString) {
var feautersListString = '';
for (var i = 0; i < features.length; i++) {
var f = features[i];
feautersListString += ('<p>' + 'Name: ' + f.name + ', is enabled: ' + f.isEnabled + ', is called from js code: ' + f.isFromJSCode + '</p>');
}
feautersListString += '<p> The image: </p>';
feautersListString += '<p>' + imageInBase64EncodedString + '</p>';
document.getElementById("features").innerHTML = feautersListString;
var afterRun = new Date().getTime();
document.getElementById("image").innerHTML = '<img src="data:image/png;base64,' + imageInBase64EncodedString + '" />';
var afterLoadedImage = new Date().getTime();
console.log("ELAPSED TIME - INSIDE LIST ALL FEATURES: " + (afterRun - beforeRun));
console.log("ELAPSED TIME - IMAGE IS LOADED TO THE <img> TAG: " + (afterLoadedImage - beforeRun));
});
}
window.onload = function() {
var browser = new Browser();
var application = new App(browser);
//Lets measure
var beforeRun = new Date().getTime();
application.Run();
var afterRun = new Date().getTime();
console.log("ELAPSED TIME - INSIDE ONLOAD: " + (afterRun - beforeRun));
}
Any help is appreciated.
I enabled the cef logging. It shows the following log
[0826/171951:ERROR:proxy_service_factory.cc(128)] Cannot use V8 Proxy resolver in single process mode.
.So I changed the SingleProcess=false in CeffSetting. Now the crashing issue is solved and then the requested webpage is not showing in cefwpfbrowser.
Now I am getting the following message from the log file
[0826/173636:VERBOSE1:pref_proxy_config_tracker_impl.cc(151)] 000000001B2A7CC0: set chrome proxy config service to 000000001B234F60
[0826/173636:VERBOSE1:pref_proxy_config_tracker_impl.cc(276)] 000000001B2A7CC0: Done pushing proxy to UpdateProxyConfig
[0826/173637:VERBOSE1:webrtc_internals.cc(85)] Could not get the download directory.
How to solve the requested page not loading issue in cefwpfbrowser.
I am using qzprint API for printing labels in my open cart extension. Everything was working fine but suddenly it stopped working on FF. In Internet explorer it works fine. If i add alerts in my functions of applet it works fine on firefox as well but not sure why not with out alerts. here is my code.
calling applet functions in my header.tpl
<script type="text/javascript">
deployQZ('<?php echo HTTP_CATALOG ?>');
useDefaultPrinter();
<script>
Applet file containing functions
function deployQZ(path) {
//alert("alert for printing label");
pathApplet = path + 'java/qz-print.jar';
pathJnlp = path + 'java/qz-print_jnlp.jnlp';
var attributes = {id: "qz", code:'qz.PrintApplet.class',
archive: pathApplet, width:1, height:1};
var parameters = {jnlp_href: pathJnlp,
cache_option:'plugin', disable_logging:'false',
initial_focus:'false'};
if (deployJava.versionCheck("1.7+") == true) {}
else if (deployJava.versionCheck("1.6+") == true) {
attributes['archive'] = 'java/jre6/qz-print.jar';
parameters['jnlp_href'] = 'java/jre6/qz-print_jnlp.jnlp';
}
deployJava.runApplet(attributes, parameters, '1.5');
}
/**
* Automatically gets called when applet has loaded.
*/
function qzReady() {
// Setup our global qz object
window["qz"] = document.getElementById('qz');
//var title = document.getElementById("title");
if (qz) {
try {
//title.innerHTML = title.innerHTML + " " + qz.getVersion();
//document.getElementById("content").style.background = "#F0F0F0";
} catch(err) { // LiveConnect error, display a detailed meesage
document.getElementById("content").style.background = "#F5A9A9";
alert("ERROR: \nThe applet did not load correctly. Communication to the " +
"applet has failed, likely caused by Java Security Settings. \n\n" +
"CAUSE: \nJava 7 update 25 and higher block LiveConnect calls " +
"once Oracle has marked that version as outdated, which " +
"is likely the cause. \n\nSOLUTION: \n 1. Update Java to the latest " +
"Java version \n (or)\n 2. Lower the security " +
"settings from the Java Control Panel.");
}
}
}
/**
* Returns is the applet is not loaded properly
*/
function isLoaded() {
if (!qz) {
alert('Error:\n\n\tPrint plugin is NOT loaded!');
return false;
} else {
try {
if (!qz.isActive()) {
alert('Error:\n\n\tPrint plugin is loaded but NOT active!');
return false;
}
} catch (err) {
alert('Error:\n\n\tPrint plugin is NOT loaded properly!');
return false;
}
}
return true;
}
function useDefaultPrinter() {
//alert("alert for printing label");
if (isLoaded()) {
// Searches for default printer
qz.findPrinter();
// Automatically gets called when "qz.findPrinter()" is finished.
window['qzDoneFinding'] = function() {
// Alert the printer name to user
var printer = qz.getPrinter();
//alert(printer !== null ? 'Default printer found: "' + printer + '"':
//'Default printer ' + 'not found');
document.getElementById("name_printer").innerHTML = 'Default printer found: "' + printer + '"';
// Remove reference to this function
window['qzDoneFinding'] = null;
defaultFound = true;
};
}
}
As u can see in my deployqz() and usedefaultprinter() functions i have alert on first line which is in comments if its commented it doesn't work in fire fox and if not commented than it works fine. With comments i get alert message from isLoaded() function "Print plugin is NOT loaded properly!".
Also in my console i get this
An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
Try this:
If the qzReady is called by the applet when ready, put useDefaultPrinter inside that function.
if isLoaded takes some time, call useDefaultPrinter in there too using setTimeout
Like this
<script type="text/javascript">
deployQZ('<?php echo HTTP_CATALOG ?>');
<script>
Applet file containing functions
var qz;
function deployQZ(path) {
pathApplet = path + 'java/qz-print.jar';
pathJnlp = path + 'java/qz-print_jnlp.jnlp';
var attributes = {id: "qz", code:'qz.PrintApplet.class',
archive: pathApplet, width:1, height:1};
var parameters = {jnlp_href: pathJnlp,
cache_option:'plugin', disable_logging:'false',
initial_focus:'false'};
if (deployJava.versionCheck("1.7+") == true) {}
else if (deployJava.versionCheck("1.6+") == true) {
attributes['archive'] = 'java/jre6/qz-print.jar';
parameters['jnlp_href'] = 'java/jre6/qz-print_jnlp.jnlp';
}
deployJava.runApplet(attributes, parameters, '1.5');
}
/**
* Automatically gets called when applet has loaded.
*/
function qzReady() {
// Setup our global qz object
qz = document.getElementById('qz');
if (qz) {
try {
useDefaultPrinter();
} catch(err) { // LiveConnect error, display a detailed meesage
document.getElementById("content").style.background = "#F5A9A9";
alert("ERROR: \nThe applet did not load correctly. Communication to the " +
"applet has failed, likely caused by Java Security Settings. \n\n" +
"CAUSE: \nJava 7 update 25 and higher block LiveConnect calls " +
"once Oracle has marked that version as outdated, which " +
"is likely the cause. \n\nSOLUTION: \n 1. Update Java to the latest " +
"Java version \n (or)\n 2. Lower the security " +
"settings from the Java Control Panel.");
}
}
else { setTimeout(useDefaultPrinter,300); }
}
/**
* Returns is the applet is not loaded properly
*/
function isLoaded() {
if (!qz) {
alert('Error:\n\n\tPrint plugin is NOT loaded!');
return false;
} else {
try {
if (!qz.isActive()) {
alert('Error:\n\n\tPrint plugin is loaded but NOT active!');
return false;
}
} catch (err) {
alert('Error:\n\n\tPrint plugin is NOT loaded properly!');
return false;
}
}
return true;
}
function useDefaultPrinter() {
//alert("alert for printing label");
if (isLoaded()) {
// Searches for default printer
qz.findPrinter();
// Automatically gets called when "qz.findPrinter()" is finished.
window['qzDoneFinding'] = function() {
// Alert the printer name to user
var printer = qz.getPrinter();
//alert(printer !== null ? 'Default printer found: "' + printer + '"':
//'Default printer ' + 'not found');
document.getElementById("name_printer").innerHTML = 'Default printer found: "' + printer + '"';
// Remove reference to this function
window['qzDoneFinding'] = null;
defaultFound = true;
};
}
else { setTimeout(useDefaultPrinter,300); }
}
I need to check every content change on a web site.
I wrote a PhantomJS function to get the whole web site. After receiving the web site I parse every row to get the data.
Now I want to hold the connection and receive all JS-updates.
What need I do to get the JS-updates?
I hope my question is clear.
Here some code explanations:
Pseudo HTML Website
<html>
<head>...</head>
<body>
<div class="value-123" onload="(function() { setInterval(retrieveData(...), 5000); })">
<!-- If retrieveData finished, VALUE will change from e.g. 1.23 to 4.235 -->
VALUE
</div>
</body>
</html>
My PhantomJS Code:
const string cEndLine = "All output received";
var sb = new StringBuilder();
var p = new PhantomJS();
p.OutputReceived += (sender, e) =>
{
if (e.Data == cEndLine)
{
callBack(sb.ToString());
}
else
{
sb.AppendLine(e.Data);
}
};
p.RunScript(#"
var page = require('webpage').create();
page.settings.loadImages = false;
page.viewportSize = { width: 1920, height: 1080 };
page.onLoadFinished = function(status) {
if (status=='success') {
setTimeout(function() {
console.log(page.content);
console.log('" + cEndLine + #"');
phantom.exit();
}," + waitAfterPageLoad.TotalMilliseconds + #");
}
};
var url = '" + url + #"';
page.open(url);", new string[0]);
I am a JavaScript newbie and learn by working on a pure JavaScript "project" that calculates mathematical functions. It all works well. Now, as a further step, I want to make the messaging multilingual. The code should be capable of loading the appropriate language file at runtime. For the dynamic loading issue, I read and found solutions on Web pages like this one.
Before writing the dynamic code, I loaded it statically and the test code worked well. The code I am asking for help about is just making the minor difference of loading a "script" element.
The code where I run into problems is the this.getString function, where it is not possible to access the de element in the language file. At line console.log(eval(language, tag));, I get the error message "Uncaught ReferenceError: de is not defined".
//File: Utils/Lang/js/FileUtils.js
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
loadFile("js/resources/lang.de.js");
return;
} ()
this.getString = function(tag, strDefault) {
console.log("getString(" + tag + ", " + strDefault + "): ");
console.log("getString(...): document = " + document);
console.log("getString(...): eval(" + language + ", " + tag + ") = ");
console.log(eval(language, tag));
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined')
? strDefault
: eval('en.' + tag);
}
}
}
The static test code that works is not included, where I can access the de element.
My question: How to load the language file properly so that the de tag is accessible?
Thank you for your help!
//File: Utils/Files/js/FileUtils.js
function loadFile(filepathname) {
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
console.log("loadFile(\"" + filepathname + "\"): document = " + document);
}
//File: Utils/Lang/js/resources/lang.de.js:
de = {
pleaseWait: "Bitte warten..."
};
//File: Utils/Lang/js/resources/lang.en.js
en = {
pleaseWait: "Please wait..."
};
//File: Utils/Lang/js/TestLanguage.js:
function output() {
console.log("output()");
var codes = ['de', 'en'];
for (var i = 0; i < codes.length; i++) {
var translator = new Language(codes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
<!--File: Utils/Lang/TestLang.html:-->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="js/Language.js"></script>
<script type="text/javascript" src="js/TestLanguage.js"></script>
</head>
<body>
<button name="outputButton" onclick="output();">Click</button>
<br>Please press [F12] so that you can see the test results.
</body>
</html>
When you add the script tag to your document, it is not loaded synchronously. You need to wait for the file to be loaded before you can use the code that was in it.
you may be able to redesign your code to use a script.onload callback:
var reference = document.createElement('script');
// ...
reference.onload = function() {
alert("Script loaded and ready");
};
but for this scenario, if you don't have many language string you may be best to just load them all statically.
How to dynamically load a script file (the most basic version, also there are multiple options to this):
function loadScriptFile(scriptPath, jsFile, callBack)
{
var scriptTag = document.createElement("script"); //creates a HTML script element
scriptTag.language = "JavaScript"; //sets the language attribute
scriptTag.type = "text/javascript";
scriptTag.src = scriptPath + jsFile + ".js"; //the source
if (callBack)
{
scriptTag.onload = callback; //when loaded execute call back
}
var scriptTagParent = document.getElementsByTagName("script")[0];
if (scriptTagParent)
{
scriptTagParent.parentNode.insertBefore(scriptTag, scriptTagParent);
}
else
{
document.body.appendChild(scriptTag);
}
}
How it works:
Run loadScriptFile("scripts", "math", startProgram). The first two arguments will point to your file and folder. The last argument is a callback function. When defined this will be executed once the script tag has finished loading and the script is available in the global scope. The script will be dynamically added to your page. If there is a script element present on the page, this will be added before that (to keep the mark up nice). If not it will be appended to the body. (this is only visual).
The callback part is the most interesting. Since your script will now be asynchronical, you'll need to use callback to tell your program that the necessary files are loaded. This callback is fired when the script file is loaded, so you won't get script errors.
Just a basic example of what I meant in my comment:
This is not an answer to your question, it's an alternative way (I think it's better to manage). Pure Javascript (with help of XML)
XML-file: language.xml
Basic XML structure:
<language>
<l1033 name="english" tag="en-US">
<id1000>
<![CDATA[
Hello World!
]]>
</id1000>
</l1033>
<l1031 name="german" tag="de-DE">
<id1000>
<![CDATA[
Hallo Welt!
]]>
</id1000>
</l1031>
</language>
What did I do:
I constructed a root element called language. Within that wrote two language strings called l1033 for English and l1031 for German. Note that a letter is prepended before the language code. XML will throw an error when a tag starts with a digit. a CDATA block is used to prevent any problems with special characters.
Now the loading will be done by AJAX:
var xmlLoader = new XMLHttpRequest();
xmlLoader.onreadystatechange = trackRequest; //event to track the request, with call back
xmlLoader.open("get", "language.xml", true); //set asynchronous to true
xmlLoader.send(null);
function trackRequest()
{
if (this.status == 200 && this.readyState == 4) //all is good
{
globalLanguageFile = this.responseXML;
startProgram(); //fictive function that starts your program
}
}
Now the XML is loaded. How to load strings from it?
function loadLanguageString(code, id, fallback)
{
var word = fallback;
if (globalLanguageFile.getElementsByTagName("l"+code).length > 0)
{
if (globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id).length > 0)
{
//found the correct language tag and id tag. Now retrieve the content with textContent.
word = globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id)[0].textContent;
}
}
return word; //when failed return fall back string
}
How to call the function:
loadLanguageString(1031, 1000, "Hello World!");
I found the right answer to my question using the info from GarethOwen. Here are the code modifications I had to do:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Arrays/js/ArrayUtils.js"></script>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="../Logic/js/LogicalUtils.js"></script>
<script type="text/javascript" src="js/LanguageUtils.js"></script>
<script type="text/javascript" src="js/TestLanguageUtils.js"></script>
</head>
<!-- body onload="load(null, '../Maths/js/resources')" -->
<body onload="load();">
<button onclick="output();">Click</button><br>
Please press [F12] so that you can see the test results.
</body>
</html>
TestLanguage.html: Augmented the body tag
<body onload="load()">
TestLanguage.js:
2a. Added the load() function requested by the HTML page now:
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < codes.length; i++) {
new Language(codes[i]);
}
}
2b. Using the global gCodes variable also in the output() function
Language.js: To test the whole better, I made the code in the function Language a little bit more elaborate by changing the line in the constructor in function Language(language) to:
// Load the proper language file:
if (eval("gLoaded.indexOf('" + language + "') < 0")) {
loadFile("js/resources/lang." + language + ".js");
gLoaded[gLoaded.length] = language;
}
Thank you for your support! :-)
//Lang/js/Lang.js:
"use strict";
/**
* Object for multilingual message handling.
*
* #param language
*/
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
switch (language) {
case "de":
loadFile("js/resources/lang.de.js");
break;
case "tr":
loadFile("js/resources/lang.tr.js");
break;
default:
loadFile("js/resources/lang.en.js");
}
return;
}()
/**
* Returns the language of that object.
*
* #returns The language
*/
this.getLanguage = function() {
var strLanguage;
switch (language) {
case "de":
strLanguage = "German";
break;
case "tr":
strLanguage = "Turkish";
break;
default:
strLanguage = "English";
}
return strLanguage;
}
/**
* Returns the language code of that object.
*
* #returns The language code
*/
this.getString = function(tag, strDefault) {
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined') ? strDefault : eval('en.' + tag);
}
}
}
//Lang/js/TestLang.js:
"use strict";
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < gCodes.length; i++) {
new Language(gCodes[i]);
}
}
/**
* Object for multilingual message handling.
*
* #param language
*/
function output() {
console.log("output()");
for (var i = 0; i < gCodes.length; i++) {
var translator = new Language(gCodes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
//Utils/Files/js/FileUtils.js:
"use strict";
/**
* Object with file utilities
*
* #param filepathname
*/
function loadFile(filepathname) {
var methodName = "loadFile(" + filepathname + "): "
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
reference.onload = function() {
console.log(methodName + "onload(): Language script loaded and ready!");
}
}
Here is the console output:
Here is the output:
load()
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!
output()
output(): in German: Bitte warten...
output(): in English: Please wait...
output(): in Turkish: Lütfen bekleyiniz...
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!
I am working on a function to track anytime there is a js error on a page. I have 4/6 error types working but can't seem to figure out a function for syntax errors, or do they just stop script execution to the point it doesn't function? Also, I am not sure how to test for internal errors? Edit: InternalError is only in firefox, but need a test for EvalError, which I will post separately. Another Edit: it appears EvalError is legacy and not fully supported by modern browsers.
No libraries such as jQuery can be used, only native js.
Here is the code with the answer added:
errorTracking = function errorCaught( ev ) {
document.getElementById('error').innerHTML = '';
var errFile = '';
var errLine = '';
if(ev.filename) { errFile = ev.filename; }
if(ev.lineno) { errLine = ev.lineno; }
var errStr = 'ERROR: ' + ev.error + ', LOCATION: ' + errFile + ', LINE NUMBER:' + errLine;
document.getElementById('error').innerHTML = '<strong>Message:</strong> ' + ev.error + '<br /><strong>Location:</strong> ' + errFile + '<br /><strong>Line Number:</strong> ' + errLine;
// Omniture Error Tracking.
//_satellite.setVar('jsError', errStr);
ev.preventDefault();
};
if(window.addEventListener) {
window.addEventListener( "error", errorTracking, false );
document.getElementById('errRef').addEventListener('click', function() {
var refErr = asdf.asdf.length;
});
document.getElementById('errTyp').addEventListener('click', function() {
var typeErrVar = null;
var typeErr = typeErrVar();
});
document.getElementById('errRan').addEventListener('click', function() {
Array.apply(null, new Array(1000000)).map(Math.random);
});
document.getElementById('errURI').addEventListener('click', function() {
decodeURIComponent("%");
});
document.getElementById('errSyn').addEventListener('click', function() {
var script = document.createElement('script');
script.text = document.getElementById('error');
document.getElementsByTagName('head')[0].appendChild(script);
});
document.getElementById('errEva').addEventListener('click', function() {
});
}
http://jsfiddle.net/swv55c35/17/
<script/>'s will be parsed completely, when a script contains a syntax-error, the entire script will be discarded. Create the syntax-error outside of the script that handles the errors, and it will work.
http://jsfiddle.net/swv55c35/3/