xml2json - "X2JS is not defined" - javascript

I'm using xml2json for the first time to get an review feed to populate on a website and I keep getting errors such as;
Uncaught ReferenceError: X2JS is not defined
and
Uncaught TypeError: Cannot set property 'X2JS' of undefined
I can't seem to find a solution, this is the code;
jQuery(document).ready(function() {
//below here
//API Feed for Testimonials
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof exports === "object") {
module.exports = factory();
} else {
root.X2JS = factory();
}
}(this, function () {
return function (config) {
'use strict';
var VERSION = "1.2.0";
config = config || {};
initConfigDefaults();
initRequiredPolyfills();
function initConfigDefaults() {
if(config.escapeMode === undefined) {
config.escapeMode = true;
}
config.attributePrefix = config.attributePrefix || "_";
config.arrayAccessForm = config.arrayAccessForm || "none";
config.emptyNodeForm = config.emptyNodeForm || "text";
if(config.enableToStringFunc === undefined) {
config.enableToStringFunc = true;
}
config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
if(config.skipEmptyTextNodesForObj === undefined) {
config.skipEmptyTextNodesForObj = true;
}
if(config.stripWhitespaces === undefined) {
config.stripWhitespaces = true;
}
config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
if(config.useDoubleQuotes === undefined) {
config.useDoubleQuotes = false;
}
config.xmlElementsFilter = config.xmlElementsFilter || [];
config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];
if(config.keepCData === undefined) {
config.keepCData = false;
}
}
var DOMNodeTypes = {
ELEMENT_NODE : 1,
TEXT_NODE : 3,
CDATA_SECTION_NODE : 4,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9
};
function initRequiredPolyfills() {
}
function getNodeLocalName( node ) {
var nodeLocalName = node.localName;
if(nodeLocalName == null) // Yeah, this is IE!!
nodeLocalName = node.baseName;
if(nodeLocalName == null || nodeLocalName=="") // =="" is IE too
nodeLocalName = node.nodeName;
return nodeLocalName;
}
function getNodePrefix(node) {
return node.prefix;
}
function escapeXmlChars(str) {
if(typeof(str) == "string")
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '&apos;');
else
return str;
}
function unescapeXmlChars(str) {
return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&apos;/g, "'").replace(/&/g, '&');
}
function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {
var idx = 0;
for(; idx < stdFiltersArrayForm.length; idx++) {
var filterPath = stdFiltersArrayForm[idx];
if( typeof filterPath === "string" ) {
if(filterPath == path)
break;
}
else
if( filterPath instanceof RegExp) {
if(filterPath.test(path))
break;
}
else
if( typeof filterPath === "function") {
if(filterPath(obj, name, path))
break;
}
}
return idx!=stdFiltersArrayForm.length;
}
function toArrayAccessForm(obj, childName, path) {
switch(config.arrayAccessForm) {
case "property":
if(!(obj[childName] instanceof Array))
obj[childName+"_asArray"] = [obj[childName]];
else
obj[childName+"_asArray"] = obj[childName];
break;
/*case "none":
break;*/
}
if(!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
if(checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {
obj[childName] = [obj[childName]];
}
}
}
function fromXmlDateTime(prop) {
// Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object
// Improved to support full spec and optional parts
var bits = prop.split(/[-T:+Z]/g);
var d = new Date(bits[0], bits[1]-1, bits[2]);
var secondBits = bits[5].split("\.");
d.setHours(bits[3], bits[4], secondBits[0]);
if(secondBits.length>1)
d.setMilliseconds(secondBits[1]);
// Get supplied time zone offset in minutes
if(bits[6] && bits[7]) {
var offsetMinutes = bits[6] * 60 + Number(bits[7]);
var sign = /\d\d-\d\d:\d\d$/.test(prop)? '-' : '+';
// Apply the sign
offsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes);
// Apply offset and local timezone
d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset())
}
else
if(prop.indexOf("Z", prop.length - 1) !== -1) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
}
// d is now a local time equivalent to the supplied time
return d;
}
function checkFromXmlDateTimePaths(value, childName, fullPath) {
if(config.datetimeAccessFormPaths.length > 0) {
var path = fullPath.split("\.#")[0];
if(checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {
return fromXmlDateTime(value);
}
else
return value;
}
else
return value;
}
function checkXmlElementsFilter(obj, childType, childName, childPath) {
if( childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {
return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);
}
else
return true;
}
function parseDOMChildren( node, path ) {
if(node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
var result = new Object;
var nodeChildren = node.childNodes;
// Alternative for firstElementChild which is not supported in some environments
for(var cidx=0; cidx <nodeChildren.length; cidx++) {
var child = nodeChildren.item(cidx);
if(child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var childName = getNodeLocalName(child);
result[childName] = parseDOMChildren(child, childName);
}
}
return result;
}
else
if(node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var result = new Object;
result.__cnt=0;
var nodeChildren = node.childNodes;
// Children nodes
for(var cidx=0; cidx <nodeChildren.length; cidx++) {
var child = nodeChildren.item(cidx); // nodeChildren[cidx];
var childName = getNodeLocalName(child);
if(child.nodeType!= DOMNodeTypes.COMMENT_NODE) {
var childPath = path+"."+childName;
if (checkXmlElementsFilter(result,child.nodeType,childName,childPath)) {
result.__cnt++;
if(result[childName] == null) {
result[childName] = parseDOMChildren(child, childPath);
toArrayAccessForm(result, childName, childPath);
}
else {
if(result[childName] != null) {
if( !(result[childName] instanceof Array)) {
result[childName] = [result[childName]];
toArrayAccessForm(result, childName, childPath);
}
}
(result[childName])[result[childName].length] = parseDOMChildren(child, childPath);
}
}
}
}
// Attributes
for(var aidx=0; aidx <node.attributes.length; aidx++) {
var attr = node.attributes.item(aidx); // [aidx];
result.__cnt++;
result[config.attributePrefix+attr.name]=attr.value;
}
// Node namespace prefix
var nodePrefix = getNodePrefix(node);
if(nodePrefix!=null && nodePrefix!="") {
result.__cnt++;
result.__prefix=nodePrefix;
}
if(result["#text"]!=null) {
result.__text = result["#text"];
if(result.__text instanceof Array) {
result.__text = result.__text.join("\n");
}
//if(config.escapeMode)
// result.__text = unescapeXmlChars(result.__text);
if(config.stripWhitespaces)
result.__text = result.__text.trim();
delete result["#text"];
if(config.arrayAccessForm=="property")
delete result["#text_asArray"];
result.__text = checkFromXmlDateTimePaths(result.__text, childName, path+"."+childName);
}
if(result["#cdata-section"]!=null) {
result.__cdata = result["#cdata-section"];
delete result["#cdata-section"];
if(config.arrayAccessForm=="property")
delete result["#cdata-section_asArray"];
}
if( result.__cnt == 0 && config.emptyNodeForm=="text" ) {
result = '';
}
else
if( result.__cnt == 1 && result.__text!=null ) {
result = result.__text;
}
else
if( result.__cnt == 1 && result.__cdata!=null && !config.keepCData ) {
result = result.__cdata;
}
else
if ( result.__cnt > 1 && result.__text!=null && config.skipEmptyTextNodesForObj) {
if( (config.stripWhitespaces && result.__text=="") || (result.__text.trim()=="")) {
delete result.__text;
}
}
delete result.__cnt;
if( config.enableToStringFunc && (result.__text!=null || result.__cdata!=null )) {
result.toString = function() {
return (this.__text!=null? this.__text:'')+( this.__cdata!=null ? this.__cdata:'');
};
}
return result;
}
else
if(node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
return node.nodeValue;
}
}
function startTag(jsonObj, element, attrList, closed) {
var resultStr = "<"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+":"):"") + element;
if(attrList!=null) {
for(var aidx = 0; aidx < attrList.length; aidx++) {
var attrName = attrList[aidx];
var attrVal = jsonObj[attrName];
if(config.escapeMode)
attrVal=escapeXmlChars(attrVal);
resultStr+=" "+attrName.substr(config.attributePrefix.length)+"=";
if(config.useDoubleQuotes)
resultStr+='"'+attrVal+'"';
else
resultStr+="'"+attrVal+"'";
}
}
if(!closed)
resultStr+=">";
else
resultStr+="/>";
return resultStr;
}
function endTag(jsonObj,elementName) {
return "</"+ (jsonObj.__prefix!=null? (jsonObj.__prefix+":"):"")+elementName+">";
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function jsonXmlSpecialElem ( jsonObj, jsonObjField ) {
if((config.arrayAccessForm=="property" && endsWith(jsonObjField.toString(),("_asArray")))
|| jsonObjField.toString().indexOf(config.attributePrefix)==0
|| jsonObjField.toString().indexOf("__")==0
|| (jsonObj[jsonObjField] instanceof Function) )
return true;
else
return false;
}
function jsonXmlElemCount ( jsonObj ) {
var elementsCnt = 0;
if(jsonObj instanceof Object ) {
for( var it in jsonObj ) {
if(jsonXmlSpecialElem ( jsonObj, it) )
continue;
elementsCnt++;
}
}
return elementsCnt;
}
function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {
return config.jsonPropertiesFilter.length == 0
|| jsonObjPath==""
|| checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);
}
function parseJSONAttributes ( jsonObj ) {
var attrList = [];
if(jsonObj instanceof Object ) {
for( var ait in jsonObj ) {
if(ait.toString().indexOf("__")== -1 && ait.toString().indexOf(config.attributePrefix)==0) {
attrList.push(ait);
}
}
}
return attrList;
}
function parseJSONTextAttrs ( jsonTxtObj ) {
var result ="";
if(jsonTxtObj.__cdata!=null) {
result+="<![CDATA["+jsonTxtObj.__cdata+"]]>";
}
if(jsonTxtObj.__text!=null) {
if(config.escapeMode)
result+=escapeXmlChars(jsonTxtObj.__text);
else
result+=jsonTxtObj.__text;
}
return result;
}
function parseJSONTextObject ( jsonTxtObj ) {
var result ="";
if( jsonTxtObj instanceof Object ) {
result+=parseJSONTextAttrs ( jsonTxtObj );
}
else
if(jsonTxtObj!=null) {
if(config.escapeMode)
result+=escapeXmlChars(jsonTxtObj);
else
result+=jsonTxtObj;
}
return result;
}
function getJsonPropertyPath(jsonObjPath, jsonPropName) {
if (jsonObjPath==="") {
return jsonPropName;
}
else
return jsonObjPath+"."+jsonPropName;
}
function parseJSONArray ( jsonArrRoot, jsonArrObj, attrList, jsonObjPath ) {
var result = "";
if(jsonArrRoot.length == 0) {
result+=startTag(jsonArrRoot, jsonArrObj, attrList, true);
}
else {
for(var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
result+=startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
result+=parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath,jsonArrObj));
result+=endTag(jsonArrRoot[arIdx],jsonArrObj);
}
}
return result;
}
function parseJSONObject ( jsonObj, jsonObjPath ) {
var result = "";
var elementsCnt = jsonXmlElemCount ( jsonObj );
if(elementsCnt > 0) {
for( var it in jsonObj ) {
if(jsonXmlSpecialElem ( jsonObj, it) || (jsonObjPath!="" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath,it))) )
continue;
var subObj = jsonObj[it];
var attrList = parseJSONAttributes( subObj )
if(subObj == null || subObj == undefined) {
result+=startTag(subObj, it, attrList, true);
}
else
if(subObj instanceof Object) {
if(subObj instanceof Array) {
result+=parseJSONArray( subObj, it, attrList, jsonObjPath );
}
else if(subObj instanceof Date) {
result+=startTag(subObj, it, attrList, false);
result+=subObj.toISOString();
result+=endTag(subObj,it);
}
else {
var subObjElementsCnt = jsonXmlElemCount ( subObj );
if(subObjElementsCnt > 0 || subObj.__text!=null || subObj.__cdata!=null) {
result+=startTag(subObj, it, attrList, false);
result+=parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath,it));
result+=endTag(subObj,it);
}
else {
result+=startTag(subObj, it, attrList, true);
}
}
}
else {
result+=startTag(subObj, it, attrList, false);
result+=parseJSONTextObject(subObj);
result+=endTag(subObj,it);
}
}
}
result+=parseJSONTextObject(jsonObj);
return result;
}
this.parseXmlString = function(xmlDocStr) {
var isIEParser = window.ActiveXObject || "ActiveXObject" in window;
if (xmlDocStr === undefined) {
return null;
}
var xmlDoc;
if (window.DOMParser) {
var parser=new window.DOMParser();
var parsererrorNS = null;
// IE9+ now is here
if(!isIEParser) {
try {
parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
}
catch(err) {
parsererrorNS = null;
}
}
try {
xmlDoc = parser.parseFromString( xmlDocStr, "text/xml" );
if( parsererrorNS!= null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
//throw new Error('Error parsing XML: '+xmlDocStr);
xmlDoc = null;
}
}
catch(err) {
xmlDoc = null;
}
}
else {
// IE :(
if(xmlDocStr.indexOf("<?")==0) {
xmlDocStr = xmlDocStr.substr( xmlDocStr.indexOf("?>") + 2 );
}
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xmlDocStr);
}
return xmlDoc;
};
this.asArray = function(prop) {
if (prop === undefined || prop == null)
return [];
else
if(prop instanceof Array)
return prop;
else
return [prop];
};
this.toXmlDateTime = function(dt) {
if(dt instanceof Date)
return dt.toISOString();
else
if(typeof(dt) === 'number' )
return new Date(dt).toISOString();
else
return null;
};
this.asDateTime = function(prop) {
if(typeof(prop) == "string") {
return fromXmlDateTime(prop);
}
else
return prop;
};
this.xml2json = function (xmlDoc) {
return parseDOMChildren ( xmlDoc );
};
this.xml_str2json = function (xmlDocStr) {
var xmlDoc = this.parseXmlString(xmlDocStr);
if(xmlDoc!=null)
return this.xml2json(xmlDoc);
else
return null;
};
this.json2xml_str = function (jsonObj) {
return parseJSONObject ( jsonObj, "" );
};
this.json2xml = function (jsonObj) {
var xmlDocStr = this.json2xml_str (jsonObj);
return this.parseXmlString(xmlDocStr);
};
this.getVersion = function () {
return VERSION;
};
}
}))
// Create x2js instance with default config
var x2js = new X2JS();
var xmlText = "";
jQuery.getJSON( "https://service1.homepro.com/smart.asmx/GetFAP_ProfileReviewsJSON?bid=141772&sort=1&page=1", function( data ) {
var xmlText = data,
x2js = new X2JS(),
jsonObj = x2js.xml_str2json( xmlText ),
html = '<div class="flex-wrapper">';
// console.log(jsonObj.SMART);
jQuery.each( jsonObj.SMART.XMLJSON, function( key, answer ) {
html += '<div class="flex-shell testimonial">';
html += '<div class="flex-item">';
html += '<div>';
html += '<span class="review-number"><i>' + answer.Quality + '</i> Quality of work</span>' ;
html += '<span class="review-number"><i>' + answer.Time + '</i> Timeliness</span>' ;
html += '<span class="review-number"><i>' + answer.Budget + '</i> Value for Money</span>' ;
html += '<span class="review-number"><i>' + answer.Courtesy + '</i> Courtesy</span>' ;
html += '<span class="review">' + answer.Testimonial + '</span>' ;
html += '<span class="name">' + answer.RefName + ' - ' + answer.refDate + '</span>';
html += '</div>';
html += '</div>';
html += '</div>';
});
jQuery('.start').html(html);
});
//above here
});
Apologies if I've gone about this in the wrong way. I've done;
npm install xml2json
Which didn't flag up any errors but I still can't seem to get the data to load correctly.

Solution that after you import <script> from package x2js, you should use window.X2JS to get constructor of X2JS. Almost packages implementing for both NPM and browser, the browser version usually use via object window, because it is shared and free connected in almost browsers.
This is my demo for the solution: https://jsfiddle.net/huynhsamha/2evdgt7r/
In my demo, I've include package x2js from NPM here https://unpkg.com/x2js#3.2.3/x2js.js
var X2JS = window.X2JS;
var x2js = new X2JS();
const data = {
a: {
b: 1
},
c: [1, 2]
}
console.log(x2js.js2xml(data))
// <a><b>1</b></a><c>1</c><c>2</c>

Related

Javascript RangeError on website proxy RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599]

Image Here
Hello! I am trying to add a search bar that acts like a proxy at the top of my website. Whenever I input a website like https://stackoverflow.com I receive an error on the website. RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599] (Note: I am using the ultraviolet service) If you'd like to test yourself the website is https://lun.netlify.app also no errors seem to appear in the console log.
importScripts('/uv/uv.bundle.js');
importScripts('/uv/uv.config.js');
class UVServiceWorker extends EventEmitter {
constructor(config = __uv$config) {
super();
if (!config.bare) config.bare = '/bare/';
this.addresses = typeof config.bare === 'string' ? [ new URL(config.bare, location) ] : config.bare.map(str => new URL(str, location));
this.headers = {
csp: [
'cross-origin-embedder-policy',
'cross-origin-opener-policy',
'cross-origin-resource-policy',
'content-security-policy',
'content-security-policy-report-only',
'expect-ct',
'feature-policy',
'origin-isolation',
'strict-transport-security',
'upgrade-insecure-requests',
'x-content-type-options',
'x-download-options',
'x-frame-options',
'x-permitted-cross-domain-policies',
'x-powered-by',
'x-xss-protection',
],
forward: [
'accept-encoding',
'connection',
'content-length',
'content-type',
'user-agent',
],
};
this.method = {
empty: [
'GET',
'HEAD'
]
};
this.statusCode = {
empty: [
204,
304,
],
};
this.config = config;
};
async fetch({ request }) {
if (!request.url.startsWith(location.origin + (this.config.prefix || '/service/'))) {
return fetch(request);
};
try {
const ultraviolet = new Ultraviolet(this.config);
if (typeof this.config.construct === 'function') {
this.config.construct(ultraviolet, 'service');
};
const db = await ultraviolet.cookie.db();
ultraviolet.meta.origin = location.origin;
ultraviolet.meta.base = ultraviolet.meta.url = new URL(ultraviolet.sourceUrl(request.url));
const requestCtx = new RequestContext(
request,
this,
ultraviolet,
!this.method.empty.includes(request.method.toUpperCase()) ? await request.blob() : null
);
if (ultraviolet.meta.url.protocol === 'blob:') {
requestCtx.blob = true;
requestCtx.base = requestCtx.url = new URL(requestCtx.url.pathname);
};
if (request.referrer && request.referrer.startsWith(location.origin)) {
const referer = new URL(ultraviolet.sourceUrl(request.referrer));
if (ultraviolet.meta.url.origin !== referer.origin && request.mode === 'cors') {
requestCtx.headers.origin = referer.origin;
};
requestCtx.headers.referer = referer.href;
};
const cookies = await ultraviolet.cookie.getCookies(db) || [];
const cookieStr = ultraviolet.cookie.serialize(cookies, ultraviolet.meta, false);
const browser = Ultraviolet.Bowser.getParser(self.navigator.userAgent).getBrowserName();
if (browser === 'Firefox' && !(request.destination === 'iframe' || request.destination === 'document')) {
requestCtx.forward.shift();
};
if (cookieStr) requestCtx.headers.cookie = cookieStr;
const reqEvent = new HookEvent(requestCtx, null, null);
this.emit('request', reqEvent);
if (reqEvent.intercepted) return reqEvent.returnValue;
const response = await fetch(requestCtx.send);
if (response.status === 500) {
return Promise.reject('');
};
const responseCtx = new ResponseContext(requestCtx, response, this);
const resEvent = new HookEvent(responseCtx, null, null);
this.emit('beforemod', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
for (const name of this.headers.csp) {
if (responseCtx.headers[name]) delete responseCtx.headers[name];
};
if (responseCtx.headers.location) {
responseCtx.headers.location = ultraviolet.rewriteUrl(responseCtx.headers.location);
};
if (responseCtx.headers['set-cookie']) {
Promise.resolve(ultraviolet.cookie.setCookies(responseCtx.headers['set-cookie'], db, ultraviolet.meta)).then(() => {
self.clients.matchAll().then(function (clients){
clients.forEach(function(client){
client.postMessage({
msg: 'updateCookies',
url: ultraviolet.meta.url.href,
});
});
});
});
delete responseCtx.headers['set-cookie'];
};
if (responseCtx.body) {
switch(request.destination) {
case 'script':
case 'worker':
responseCtx.body = `if (!self.__uv && self.importScripts) importScripts('${__uv$config.bundle}', '${__uv$config.config}', '${__uv$config.handler}');\n`;
responseCtx.body += ultraviolet.js.rewrite(
await response.text()
);
break;
case 'style':
responseCtx.body = ultraviolet.rewriteCSS(
await response.text()
);
break;
case 'iframe':
case 'document':
if (isHtml(ultraviolet.meta.url, (responseCtx.headers['content-type'] || ''))) {
responseCtx.body = ultraviolet.rewriteHtml(
await response.text(),
{
document: true ,
injectHead: ultraviolet.createHtmlInject(
this.config.handler,
this.config.bundle,
this.config.config,
ultraviolet.cookie.serialize(cookies, ultraviolet.meta, true),
request.referrer
)
}
);
};
};
};
if (requestCtx.headers.accept === 'text/event-stream') {
responseCtx.headers['content-type'] = 'text/event-stream';
};
this.emit('response', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
return new Response(responseCtx.body, {
headers: responseCtx.headers,
status: responseCtx.status,
statusText: responseCtx.statusText,
});
} catch(err) {
return new Response(err.toString(), {
status: 500,
});
};
};
getBarerResponse(response) {
const headers = {};
const raw = JSON.parse(response.headers.get('x-bare-headers'));
for (const key in raw) {
headers[key.toLowerCase()] = raw[key];
};
return {
headers,
status: +response.headers.get('x-bare-status'),
statusText: response.headers.get('x-bare-status-text'),
body: !this.statusCode.empty.includes(+response.headers.get('x-bare-status')) ? response.body : null,
};
};
get address() {
return this.addresses[Math.floor(Math.random() * this.addresses.length)];
};
static Ultraviolet = Ultraviolet;
};
self.UVServiceWorker = UVServiceWorker;
class ResponseContext {
constructor(request, response, worker) {
const { headers, status, statusText, body } = !request.blob ? worker.getBarerResponse(response) : {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
body: response.body,
};
this.request = request;
this.raw = response;
this.ultraviolet = request.ultraviolet;
this.headers = headers;
this.status = status;
this.statusText = statusText;
this.body = body;
};
get url() {
return this.request.url;
}
get base() {
return this.request.base;
};
set base(val) {
this.request.base = val;
};
};
class RequestContext {
constructor(request, worker, ultraviolet, body = null) {
this.ultraviolet = ultraviolet;
this.request = request;
this.headers = Object.fromEntries([...request.headers.entries()]);
this.method = request.method;
this.forward = [...worker.headers.forward];
this.address = worker.address;
this.body = body || null;
this.redirect = request.redirect;
this.credentials = 'omit';
this.mode = request.mode === 'cors' ? request.mode : 'same-origin';
this.blob = false;
};
get send() {
return new Request((!this.blob ? this.address.href + 'v1/' : 'blob:' + location.origin + this.url.pathname), {
method: this.method,
headers: {
'x-bare-protocol': this.url.protocol,
'x-bare-host': this.url.hostname,
'x-bare-path': this.url.pathname + this.url.search,
'x-bare-port': this.url.port || (this.url.protocol === 'https:' ? '443' : '80'),
'x-bare-headers': JSON.stringify(this.headers),
'x-bare-forward-headers': JSON.stringify(this.forward),
},
redirect: this.redirect,
credentials: this.credentials,
mode: location.origin !== this.address.origin ? 'cors' : this.mode,
body: this.body
});
};
get url() {
return this.ultraviolet.meta.url;
};
set url(val) {
this.ultraviolet.meta.url = val;
};
get base() {
return this.ultraviolet.meta.base;
};
set base(val) {
this.ultraviolet.meta.base = val;
};
}
function isHtml(url, contentType = '') {
return (Ultraviolet.mime.contentType((contentType || url.pathname)) || 'text/html').split(';')[0] === 'text/html';
};
class HookEvent {
#intercepted;
#returnValue;
constructor(data = {}, target = null, that = null) {
this.#intercepted = false;
this.#returnValue = null;
this.data = data;
this.target = target;
this.that = that;
};
get intercepted() {
return this.#intercepted;
};
get returnValue() {
return this.#returnValue;
};
respondWith(input) {
this.#returnValue = input;
this.#intercepted = true;
};
};
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
throw er;
}
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err;
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
emitter.addEventListener(name, function wrapListener(arg) {
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}

How can i set customize Form in add event of wdCalender?

i want to set my own customize form in wdCalendar add event like first name last name instead of "what". where in jquery.calendar.js i find quickadd function which one is used when user click on calendar to add event then form appear help of quickadd function but i dont know how to set custom field in this function so please help me
below one is quickadd function of jquery.calender.js
function quickadd(start, end, isallday, pos) {
if ((!option.quickAddHandler && option.quickAddUrl == "") || option.readonly) {
return;
}
var buddle = $("#bbit-cal-buddle");
if (buddle.length == 0) {
var temparr = [];
temparr.push('<div id="bbit-cal-buddle" style="z-index: 180; width: 400px;visibility:hidden;" class="bubble">');
temparr.push('<table class="bubble-table" cellSpacing="0" cellPadding="0"><tbody><tr><td class="bubble-cell-side"><div id="tl1" class="bubble-corner"><div class="bubble-sprite bubble-tl"></div></div>');
temparr.push('<td class="bubble-cell-main"><div class="bubble-top"></div><td class="bubble-cell-side"><div id="tr1" class="bubble-corner"><div class="bubble-sprite bubble-tr"></div></div> <tr><td class="bubble-mid" colSpan="3"><div style="overflow: hidden" id="bubbleContent1"><div><div></div><div class="cb-root">');
temparr.push('<table class="cb-table" cellSpacing="0" cellPadding="0"><tbody><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.time, ':</th><td class=cb-value><div id="bbit-cal-buddle-timeshow"></div></td></tr><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.content, ':</th><td class="cb-value"><div class="textbox-fill-wrapper"><div class="textbox-fill-mid"><input id="bbit-cal-what" class="textbox-fill-input"/></div></div><div class="cb-example">');
temparr.push(i18n.xgcalendar.example, '</div></td></tr></tbody></table><input id="bbit-cal-start" type="hidden"/><input id="bbit-cal-end" type="hidden"/><input id="bbit-cal-allday" type="hidden"/><input id="bbit-cal-quickAddBTN" value="');
temparr.push(i18n.xgcalendar.create_event, '" type="button"/> <SPAN id="bbit-cal-editLink" class="lk">');
temparr.push(i18n.xgcalendar.update_detail, ' <StrONG>>></StrONG></SPAN></div></div></div><tr><td><div id="bl1" class="bubble-corner"><div class="bubble-sprite bubble-bl"></div></div><td><div class="bubble-bottom"></div><td><div id="br1" class="bubble-corner"><div class="bubble-sprite bubble-br"></div></div></tr></tbody></table><div id="bubbleClose1" class="bubble-closebutton"></div><div id="prong2" class="prong"><div class=bubble-sprite></div></div></div>');
var tempquickAddHanler = temparr.join("");
temparr = null;
$(document.body).append(tempquickAddHanler);
buddle = $("#bbit-cal-buddle");
var calbutton = $("#bbit-cal-quickAddBTN");
var lbtn = $("#bbit-cal-editLink");
var closebtn = $("#bubbleClose1").click(function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
calbutton.click(function(e) {
if (option.isloading) {
return false;
}
option.isloading = true;
var what = $("#bbit-cal-what").val();
var datestart = $("#bbit-cal-start").val();
var dateend = $("#bbit-cal-end").val();
var allday = $("#bbit-cal-allday").val();
var f = /^[^\$\<\>]+$/.test(what);
if (!f) {
alert(i18n.xgcalendar.invalid_title);
$("#bbit-cal-what").focus();
option.isloading = false;
return false;
}
var zone = new Date().getTimezoneOffset() / 60 * -1;
var param = [{ "name": "CalendarTitle", value: what },
{ "name": "CalendarStartTime", value: datestart },
{ "name": "CalendarEndTime", value: dateend },
{ "name": "IsAllDayEvent", value: allday },
{ "name": "timezone", value: zone}];
if (option.extParam) {
for (var pi = 0; pi < option.extParam.length; pi++) {
param[param.length] = option.extParam[pi];
}
}
if (option.quickAddHandler && $.isFunction(option.quickAddHandler)) {
option.quickAddHandler.call(this, param);
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
else {
$("#bbit-cal-buddle").css("visibility", "hidden");
var newdata = [];
var tId = -1;
option.onBeforeRequestData && option.onBeforeRequestData(2);
$.post(option.quickAddUrl, param, function(data) {
if (data) {
if (data.IsSuccess == true) {
option.isloading = false;
option.eventItems[tId][0] = data.Data;
option.eventItems[tId][8] = 1;
render();
option.onAfterRequestData && option.onAfterRequestData(2);
}
else {
option.onRequestDataError && option.onRequestDataError(2, data);
option.isloading = false;
option.onAfterRequestData && option.onAfterRequestData(2);
}
}
}, "json");
newdata.push(-1, what);
var sd = strtodate(datestart);
var ed = strtodate(dateend);
var diff = DateDiff("d", sd, ed);
newdata.push(sd, ed, allday == "1" ? 1 : 0, diff > 0 ? 1 : 0, 0);
newdata.push(-1, 0, "", "");
tId = Ind(newdata);
realsedragevent();
render();
}
});
lbtn.click(function(e) {
if (!option.EditCmdhandler) {
alert("EditCmdhandler" + i18n.xgcalendar.i_undefined);
}
else {
if (option.EditCmdhandler && $.isFunction(option.EditCmdhandler)) {
option.EditCmdhandler.call(this, ['0', $("#bbit-cal-what").val(), $("#bbit-cal-start").val(), $("#bbit-cal-end").val(), $("#bbit-cal-allday").val()]);
}
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
return false;
});
buddle.mousedown(function(e) { return false });
}
var dateshow = CalDateShow(start, end, !isallday, true);
var off = getbuddlepos(pos.left, pos.top);
if (off.hide) {
$("#prong2").hide()
}
else {
$("#prong2").show()
}
$("#bbit-cal-buddle-timeshow").html(dateshow);
var calwhat = $("#bbit-cal-what").val("");
$("#bbit-cal-allday").val(isallday ? "1" : "0");
$("#bbit-cal-start").val(dateFormat.call(start, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
$("#bbit-cal-end").val(dateFormat.call(end, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
buddle.css({ "visibility": "visible", left: off.left, top: off.top });
calwhat.blur().focus(); //add 2010-01-26 blur() fixed chrome
$(document).one("mousedown", function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
return false;
}
could i add ajax link on add event and display custom form and add data to database ?
is there any solution of this type to direct open popup as in add event as like open in edit event ?
And Here we go..
just copy paste this code in your jquery.form.js
it will provide you and extra field to input text.
jquery.form.js
<script>
(function($) {
$.fn.ajaxSubmit = function(options) {
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n])
a.push( { name: n, value: options.data[n][k] } )
}
else
a.push( { name: n, value: options.data[n] } );
}
}
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null;
}
else
options.data = q;
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i].apply(options, [data, status, $form]);
};
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
if (options.iframe || found) {
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
this.trigger('form-submit-notify', [this, options]);
return this;
function fileUpload() {
var form = $form[0];
if ($(':input[#name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}
var opts = $.extend({}, $.ajaxSettings, options);
var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
if ($.browser.msie || $.browser.opera)
io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = {
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function() {
this.aborted = 1;
$io.attr('src','about:blank');
}
};
var g = opts.global;
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
if (s.beforeSend && s.beforeSend(xhr, s) === false) {
s.global && jQuery.active--;
return;
}
if (xhr.aborted)
return;
var cbInvoked = 0;
var timedOut = 0;
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}
setTimeout(function() {
var t = $form.attr('target'), a = $form.attr('action');
$form.attr({
target: id,
method: 'POST',
action: opts.url
});
if (! options.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
$form.attr('action', a);
t ? $form.attr('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var operaHack = 0;
var ok = true;
try {
if (timedOut) throw 'timeout';
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (doc.body == null && !operaHack && $.browser.opera) {
operaHack = 1;
cbInvoked--;
setTimeout(cb, 100);
return;
}
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};
if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
$(this).ajaxSubmit(options);
return false;
}).each(function() {
$(":submit,input:image", this).bind('click.form-plugin',function(e) {
var form = this.form;
form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - this.offsetLeft;
form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
});
});
};
$.fn.ajaxFormUnbind = function() {
this.unbind('submit.form-plugin');
return this.each(function() {
$(":submit,input:image", this).unbind('click.form-plugin');
});
};
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
$.fn.formSerialize = function(semantic) {
return $.param(this.formToArray(semantic));
};
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
return $.param(a);
};
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
$.fn.resetForm = function() {
return this.each(function() {
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b
});
};
$.fn.selected = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);
</script>

Factory pattern within Angular?

Someone mentioned I should use a true Factory pattern below so I don't have to constantly supply the typeName. How can this be accomplished within JavaScript and Angular. If it were C#, I wouldn't have a problem, but the Java reference / value types and Angular are making my brain hurt.
(function () {
'use strict';
angular
.module('blocks.object-cache');
objectCache.$inject = ['CacheFactory', '$auth'];
function objectCache(CacheFactory, $auth) {
var _options = {
maxAge : (60 * 60 * 1000),
deleteOnExpire : 'passive',
storageMode : 'localStorage'
};
var service = {
setOptions : setOptions,
getCache : getCache,
clear : clear,
getAll : getAll,
getItem : getItem,
getItems : getItems,
putItem : putItem,
putItems : putItems,
getItemsByKey : getItemsByKey,
getItemByKeyFirst : getItemByKeyFirst,
getItemByKeySingle : getItemByKeySingle,
removeItemsByKey : removeItemsByKey,
removeItemByKey : removeItemByKey,
putItemsByKey : putItemsByKey,
putItemByKey : putItemByKey
};
return service;
////////////////////////////////////////////////////////////////////////////////
function setOptions (options) {
options = options || {};
options.maxAge = options.maxAge = _options.maxAge;
options.deleteOnExpire = options.deleteOnExpire = _options.deleteOnExpire;
options.storageMode = options.storageMode = _options.storageMode;
_options = options;
}
function getCache(typeName) {
var cacheName = [getUserId(), normalizeTypeName(typeName || 'objects')].join('_');
var cache = CacheFactory(cacheName);
if (cache) { return cache; }
cache = CacheFactory(cacheName, _options);
return cache;
}
function clear (typeName) {
var cache = getCache(typeName);
cache.removeAll();
return (!cache.keys() || (cache.keys().length < 1));
}
function getAll (typeName) {
var cache = getCache(typeName);
var result = [];
(cache.keys() || []).forEach(function(key){
result.push(cache(key));
});
return result;
}
function getItem(typeName, id) {
if (typeof id == 'undefined' || !id.trim) { return null; }
var cache = getCache(typeName);
return cache.get(id);
}
function getItems(typeName, ids) {
var cache = getCache(typeName),
result = [],
_ids = [];
(ids || []).forEach(function(id){
if (_ids.indexOf(id) < 0) {
_ids.push(id);
var item = cache.get(id);
if (item) { result.push(item); }
}
});
return result;
}
function putItem(typeName, item, id, refresh) {
if (typeof item == 'undefined') { return false; }
if (typeof id == 'undefined' || !id.trim) { return false; }
var cache = getCache(typeName);
var existing = cache.get(id);
if (existing && !refresh) { return true; }
if (existing) { cache.remove(id); }
cache.put(item, id);
return (!!cache.get(id));
}
function putItems(typeName, items, idField, refresh) {
var cache = getCache(typeName);
(items || []).forEach(function(item){
var id = item[idField];
if (typeof id != 'undefined') {
var existing = cache.get(id);
if (existing && !!refresh) { cache.remove(id); }
if (!existing || !!refresh) { cache.put(item, id); }
if (!cache.get(id)) { return false; }
}
});
return true;
}
function getItemsByKey(typeName, key, value, isCaseSensitive) {
var result = [];
(getAll(typeName) || []).forEach(function(item){
var itemValue = item[key];
if (typeof itemValue != 'undefined') {
if ((typeof value == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || value.toLowerCase() == itemValue.toLowerCase())) {
result.push(item);
} else if (((typeof value) == (typeof itemValue)) && (value == itemValue)) {
result.push(item);
} else {
// Other scenarios?
}
}
});
return result;
}
function getItemByKeyFirst(typeName, key, value, isCaseSensitive) {
var items = getItemsByKey(typeName, key, value, isCaseSensitive) || [];
return (items.length > 0) ? items[0] : null;
}
function getItemByKeySingle(typeName, key, value, isCaseSensitive) {
var items = getItemsByKey(typeName, key, value, isCaseSensitive) || [];
return (items.length === 0) ? items[0] : null;
}
function removeItemsByKey (typeName, keyField, values, isCaseSensitive) {
var cache = getCache(typeName),
keysToRemove = [];
(cache.keys() || []).forEach(function(key){
var item = cache.get[key],
itemValue = item[keyField];
if (typeof itemValue != 'undefined') {
for (var v = 0; v < (values || []).length; v += 1) {
if ((typeof values[v] == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || values[v].toLowerCase() == itemValue.toLowerCase())) {
keysToRemove.push(key);
break;
} else if (((typeof values[v]) == (typeof itemValue)) && (values[v] == itemValue)) {
keysToRemove.push(key);
break;
} else {
// Other scenarios?
}
}
}
});
var success = true;
keysToRemove.forEach(function(key){
cache.remove(key);
if (cache.get(key)) { success = false; }
});
return success;
}
function removeItemByKey (typeName, keyField, value, isCaseSensitive) {
return removeItemsByKey(typeName, keyField, [value], isCaseSensitive);
}
function putItemsByKey(typeName, items, keyField, refresh, isCaseSensitive) {
if (!!refresh) {
var values = _.map((items || []), keyField);
if (!removeItemsByKey(typeName, keyField, values, isCaseSensitive)) { return false; }
}
var cache = getCache(typeName);
(items || []).forEach(function(item){
var id = item[keyField];
if (typeof value != 'undefined') { cache.put(item, id); }
if (!cache.get(id)) { return false; }
});
return true;
}
function putItemByKey(typeName, item, keyField, refresh, isCaseSensitive) {
return putItemsByKey(typeName, [item], keyField, refresh, isCaseSensitive);
}
function getUserId () {
return $auth.isAuthenticated() ? ($auth.getPayload().sub || 'unknown') : 'public';
}
function normalizeTypeName (typeName) {
return typeName.split('.').join('-');
}
}
})();
I'm not an Angular guru, but couldn't you just move the functions to achieve a factory-like pattern? I have not tested this, but with about two minutes of copy-n-paste...
Edit: Removed your nested iterate functions.
(function () {
'use strict';
angular
.module('blocks.object-cache')
.service('ObjectCache', ObjectCache);
ObjectCache.$inject = ['CacheFactory', '$auth'];
function ObjectCache(CacheFactory, $auth) {
var _options = {
maxAge : (60 * 60 * 1000),
deleteOnExpire : 'passive',
storageMode : 'localStorage'
};
var factory = {
getCache : getCache
};
return factory;
////////////////////////////
function getCache(typeName, options) {
options = options || {};
options.maxAge = options.maxAge = _options.maxAge;
options.deleteOnExpire = options.deleteOnExpire = _options.deleteOnExpire;
options.storageMode = options.storageMode = _options.storageMode;
typeName = normalizeTypeName(typeName || 'objects');
var userId = getUserId() || 'public';
var name = userId + '_' + typeName;
var service = {
type : typeName,
user : userId,
name : name,
options : options,
cache : CacheFactory(name) || CacheFactory.createCache(name, options),
clear : function () {
this.cache.removeAll();
},
getAll : function () {
var result = [];
var keys = this.cache.keys() || [];
for (var i = 0; i < keys.length; i += 1) {
result.push(this.cache(keys[i]));
}
return result;
},
getItems : function (ids) {
var result = [],
_ids = [];
for (var i = 0; i < (ids || []).length; i += 1) {
var id = ids[i];
if (_ids.indexOf(id) < 0) {
_ids.push(id);
var item = this.cache.get(id);
if (item) { result.push(item); }
}
}
return result;
},
getItem : function (id) {
var items = this.getItems([id]);
return (items.length > 0) ? items[0] : null;
},
putItem : function (item, id, refresh) {
var existing = this.cache.get(id);
if (existing && !refresh) { return true; }
if (existing) { this.cache.remove(id); }
this.cache.put(item, id);
return (!!this.cache.get(id));
},
putItems : function (items, idField, refresh) {
var success = true;
for (var i = 0; i < (items || []).length; i += 1) {
var item = items[i];
var id = item[idField];
if (typeof id != 'undefined') {
if (this.putItem(item, id, refresh)) { success = false; }
}
}
return success;
},
getItemsByKey : function (key, value, isCaseSensitive) {
var result = [];
(this.getAll() || []).forEach(function(item){
var itemValue = item[key];
if (typeof itemValue != 'undefined') {
if ((typeof value == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || value.toLowerCase() == itemValue.toLowerCase())) {
result.push(item);
} else if (((typeof value) == (typeof itemValue)) && (value == itemValue)) {
result.push(item);
} else {
// Other scenarios?
}
}
});
return result;
},
getItemByKeyFirst : function (key, value, isCaseSensitive) {
var items = this.getItemsByKey(key, value, isCaseSensitive) || [];
return (items.length > 0) ? items[0] : null;
},
getItemByKeySingle : function (key, value, isCaseSensitive) {
var items = this.getItemsByKey(key, value, isCaseSensitive) || [];
return (items.length === 0) ? items[0] : null;
},
removeItemsByKey : function (keyField, values, isCaseSensitive) {
var keysToRemove = [],
keys = this.cache.keys() || [];
for (var k = 0; k < keys.length; k += 1) {
var key = keys[k];
var item = this.cache.get(key);
var itemVal = item[keyField];
if (typeof itemVal != 'undefined') {
for (var v = 0; v < (values || []).length; v += 1) {
if ((typeof values[v] == 'string') && (typeof itemVal == 'string') && (!isCaseSensitive || values[v].toLowerCase() == itemVal.toLowerCase())) {
keysToRemove.push(key);
break;
} else if (((typeof values[v]) == (typeof itemVal)) && (values[v] == itemVal)) {
keysToRemove.push(key);
break;
} else {
// Other scenarios?
}
}
}
}
var success = true;
for (var r = 0; r < keysToRemove.length; r += 1) {
this.cache.remove(keysToRemove[r]);
if (this.cache.get(keysToRemove[r])) { success = false; }
}
return success;
},
removeItemByKey : function (keyField, value, isCaseSensitive) {
return this.removeItemsByKey(keyField, [value], isCaseSensitive);
},
putItemsByKey : function(items, keyField, refresh, isCaseSensitive) {
if (!!refresh) {
var values = _.map((items || []), keyField);
if (!this.removeItemsByKey(keyField, values, isCaseSensitive)) { return false; }
}
for (var i = 0; i < (items || []).length; i += 1) {
var id = items[i][keyField];
if (typeof id != 'undefined') {
this.cache.put(items[i], id);
if (!this.cache.get(id)) { return false; }
}
}
return true;
},
putItemByKey : function (item, keyField, refresh, isCaseSensitive) {
return this.putItemsByKey([item], keyField, refresh, isCaseSensitive);
}
};
return service;
}
function getUserId () {
return $auth.isAuthenticated() ? ($auth.getPayload().sub || 'unknown') : null;
}
function normalizeTypeName (typeName) {
return typeName.split('.').join('-');
}
}
})();

How to check if object.subobject.subsubobject exists or not in javascript?

The hierarchy can be very deep, So how to check if the a property exists somewhere within the root object ? If not then create it.
I have the following html
<div id="container">
<div id="level-1">
<input id="value-1" group="a.b" name="c" value="some-value-1">
</div>
</div>
Now i would like to put the value of this input into a javascript object based on the parent attribute.
Desired output is
{
"a" : {
"b" : {
"c" : "some-value-1"
}
}
}
My Effort :
function traverse(id, obj) {
var methodName = "traverse";
var elementToTraverse = document.getElementById(id);
var currentElementLength = elementToTraverse.childNodes.length;
if (currentElementLength > 0) {
var children = getChildNodes(elementToTraverse);
for (var ch in children) {
var currentChild = children[ch];
//ignore the text nodes
if (currentChild.nodeType == 3) {
continue;
}
if (currentChild.nodeType == 1 && currentChild.childNodes.length > 0 && currentChild.id != "") {
//call without the object argument as it has already been constructed.
traverse(currentChild.id, obj);
}
else if (currentChild.nodeType == 1 && currentChild.id != "" && currentChild.getAttribute('name') != null) {
if (DEBUG) {
logOnConsole(methodName, currentChild.getAttribute('name') + "--" + currentChild.id, logLevel.INFO);
}
var group = currentChild.getAttribute('group') || null;
var name = currentChild.getAttribute('name');
var value = getValue(currentChild);
if (value == "" || value == undefined) {
if(group){
if(isNull(obj[group])){
obj[group] = new Object();
}
obj[group][name] = "";
}
else{
obj[name] = "";
}
}
else if(group){
if(isNull(obj[group])){
obj[group] = new Object();
}
obj[group][name] = value;
}
else {
obj[name] = value;
}
}
else {
if (DEBUG) {
logOnConsole(methodName, "Element not useful. \n" + currentChild.nodeName, logLevel.INFO);
}
}
}
}
return obj;
}
I call it via traverse('container-id', new Object()) but this will work for a single value in the group rather than a nested structure.
Try this
function isExist(obj, path) {
patharray = path.split(".");
for(var i=0;i < patharray.length; i++) {
obj = obj[patharray[i]];
if(obj === undefined) return false
}
return true;
}
document.body.innerHTML = isExist({subobject:{subsubobject:{test: 34}}}, 'subobject.subsubobject');

Detecting Java version (runnable in browser) with JavaScript?

I was checking this code provided by Sun that can retrieve a list of the Java Runtime Environments installed on the machine. Here's the code formatted and with some functions removed so it's easier to read:
var deployJava = {
debug: null,
firefoxJavaVersion: null,
returnPage: null,
locale: null,
oldMimeType: 'application/npruntime-scriptable-plugin;DeploymentToolkit',
mimeType: 'application/java-deployment-toolkit',
browserName: null,
browserName2: null,
getJREs: function () {
var list = new Array();
if (deployJava.isPluginInstalled()) {
var plugin = deployJava.getPlugin();
var VMs = plugin.jvms;
for (var i = 0; i < VMs.getLength(); i++) {
list[i] = VMs.get(i).version;
}
} else {
var browser = deployJava.getBrowser();
if (browser == 'MSIE') {
if (deployJava.testUsingActiveX('1.7.0')) {
list[0] = '1.7.0';
} else if (deployJava.testUsingActiveX('1.6.0')) {
list[0] = '1.6.0';
} else if (deployJava.testUsingActiveX('1.5.0')) {
list[0] = '1.5.0';
} else if (deployJava.testUsingActiveX('1.4.2')) {
list[0] = '1.4.2';
} else if (deployJava.testForMSVM()) {
list[0] = '1.1';
}
} else if (browser == 'Netscape Family') {
deployJava.getJPIVersionUsingMimeType();
if (deployJava.firefoxJavaVersion != null) {
list[0] = deployJava.firefoxJavaVersion;
} else if (deployJava.testUsingMimeTypes('1.7')) {
list[0] = '1.7.0';
} else if (deployJava.testUsingMimeTypes('1.6')) {
list[0] = '1.6.0';
} else if (deployJava.testUsingMimeTypes('1.5')) {
list[0] = '1.5.0';
} else if (deployJava.testUsingMimeTypes('1.4.2')) {
list[0] = '1.4.2';
} else if (deployJava.browserName2 == 'Safari') {
if (deployJava.testUsingPluginsArray('1.7.0')) {
list[0] = '1.7.0';
} else if (deployJava.testUsingPluginsArray('1.6')) {
list[0] = '1.6.0';
} else if (deployJava.testUsingPluginsArray('1.5')) {
list[0] = '1.5.0';
} else if (deployJava.testUsingPluginsArray('1.4.2')) {
list[0] = '1.4.2';
}
}
}
}
if (deployJava.debug) {
for (var i = 0; i < list.length; ++i) {
alert('We claim to have detected Java SE ' + list[i]);
}
}
return list;
},
runApplet: function (attributes, parameters, minimumVersion) {
if (minimumVersion == 'undefined' || minimumVersion == null) {
minimumVersion = '1.1';
}
var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";
var matchData = minimumVersion.match(regex);
if (deployJava.returnPage == null) {
deployJava.returnPage = document.location;
}
if (matchData != null) {
var browser = deployJava.getBrowser();
if ((browser != '?') && ('Safari' != deployJava.browserName2)) {
if (deployJava.versionCheck(minimumVersion + '+')) {
deployJava.writeAppletTag(attributes, parameters);
}
} else {
deployJava.writeAppletTag(attributes, parameters);
}
} else {
if (deployJava.debug) {
alert('Invalid minimumVersion argument to runApplet():' + minimumVersion);
}
}
},
writeAppletTag: function (attributes, parameters) {
var startApplet = '<' + 'applet ';
var params = '';
var endApplet = '<' + '/' + 'applet' + '>';
var addCodeAttribute = true;
for (var attribute in attributes) {
startApplet += (' ' + attribute + '="' + attributes[attribute] + '"');
if (attribute == 'code' || attribute == 'java_code') {
addCodeAttribute = false;
}
}
if (parameters != 'undefined' && parameters != null) {
var codebaseParam = false;
for (var parameter in parameters) {
if (parameter == 'codebase_lookup') {
codebaseParam = true;
}
if (parameter == 'object' || parameter == 'java_object') {
addCodeAttribute = false;
}
params += '<param name="' + parameter + '" value="' + parameters[parameter] + '"/>';
}
if (!codebaseParam) {
params += '<param name="codebase_lookup" value="false"/>';
}
}
if (addCodeAttribute) {
startApplet += (' code="dummy"');
}
startApplet += '>';
document.write(startApplet + '\n' + params + '\n' + endApplet);
},
versionCheck: function (versionPattern) {
var index = 0;
var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?(\\*|\\+)?$";
var matchData = versionPattern.match(regex);
if (matchData != null) {
var familyMatch = true;
var patternArray = new Array();
for (var i = 1; i < matchData.length; ++i) {
if ((typeof matchData[i] == 'string') && (matchData[i] != '')) {
patternArray[index] = matchData[i];
index++;
}
}
if (patternArray[patternArray.length - 1] == '+') {
familyMatch = false;
patternArray.length--;
} else {
if (patternArray[patternArray.length - 1] == '*') {
patternArray.length--;
}
}
var list = deployJava.getJREs();
for (var i = 0; i < list.length; ++i) {
if (deployJava.compareVersionToPattern(list[i], patternArray, familyMatch)) {
return true;
}
}
return false;
} else {
alert('Invalid versionPattern passed to versionCheck: ' + versionPattern);
return false;
}
},
isWebStartInstalled: function (minimumVersion) {
var browser = deployJava.getBrowser();
if ((browser == '?') || ('Safari' == deployJava.browserName2)) {
return true;
}
if (minimumVersion == 'undefined' || minimumVersion == null) {
minimumVersion = '1.4.2';
}
var retval = false;
var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";
var matchData = minimumVersion.match(regex);
if (matchData != null) {
retval = deployJava.versionCheck(minimumVersion + '+');
} else {
if (deployJava.debug) {
alert('Invalid minimumVersion argument to isWebStartInstalled(): ' + minimumVersion);
}
retval = deployJava.versionCheck('1.4.2+');
}
return retval;
},
getJPIVersionUsingMimeType: function () {
for (var i = 0; i < navigator.mimeTypes.length; ++i) {
var s = navigator.mimeTypes[i].type;
var m = s.match(/^application\/x-java-applet;jpi-version=(.*)$/);
if (m != null) {
deployJava.firefoxJavaVersion = m[1];
if ('Opera' != deployJava.browserName2) {
break;
}
}
}
},
isPluginInstalled: function () {
var plugin = deployJava.getPlugin();
if (plugin && plugin.jvms) {
return true;
} else {
return false;
}
},
isPlugin2: function () {
if (deployJava.isPluginInstalled()) {
if (deployJava.versionCheck('1.6.0_10+')) {
try {
return deployJava.getPlugin().isPlugin2();
} catch (err) {}
}
}
return false;
},
allowPlugin: function () {
deployJava.getBrowser();
var ret = ('Safari' != deployJava.browserName2 && 'Opera' != deployJava.browserName2);
return ret;
},
getPlugin: function () {
deployJava.refresh();
var ret = null;
if (deployJava.allowPlugin()) {
ret = document.getElementById('deployJavaPlugin');
}
return ret;
},
compareVersionToPattern: function (version, patternArray, familyMatch) {
var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";
var matchData = version.match(regex);
if (matchData != null) {
var index = 0;
var result = new Array();
for (var i = 1; i < matchData.length; ++i) {
if ((typeof matchData[i] == 'string') && (matchData[i] != '')) {
result[index] = matchData[i];
index++;
}
}
var l = Math.min(result.length, patternArray.length);
if (familyMatch) {
for (var i = 0; i < l; ++i) {
if (result[i] != patternArray[i]) return false;
}
return true;
} else {
for (var i = 0; i < l; ++i) {
if (result[i] < patternArray[i]) {
return false;
} else if (result[i] > patternArray[i]) {
return true;
}
}
return true;
}
} else {
return false;
}
},
getBrowser: function () {
if (deployJava.browserName == null) {
var browser = navigator.userAgent.toLowerCase();
if (deployJava.debug) {
alert('userAgent -> ' + browser);
}
if (browser.indexOf('msie') != -1) {
deployJava.browserName = 'MSIE';
deployJava.browserName2 = 'MSIE';
} else if (browser.indexOf('iphone') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'iPhone';
} else if (browser.indexOf('firefox') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Firefox';
} else if (browser.indexOf('chrome') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Chrome';
} else if (browser.indexOf('safari') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Safari';
} else if (browser.indexOf('mozilla') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Other';
} else if (browser.indexOf('opera') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Opera';
} else {
deployJava.browserName = '?';
deployJava.browserName2 = 'unknown';
}
if (deployJava.debug) {
alert('Detected browser name:' + deployJava.browserName + ', ' + deployJava.browserName2);
}
}
return deployJava.browserName;
},
testUsingActiveX: function (version) {
var objectName = 'JavaWebStart.isInstalled.' + version + '.0';
if (!ActiveXObject) {
if (deployJava.debug) {
alert('Browser claims to be IE, but no ActiveXObject object?');
}
return false;
}
try {
return (new ActiveXObject(objectName) != null);
} catch (exception) {
return false;
}
},
testForMSVM: function () {
var clsid = '{08B0E5C0-4FCB-11CF-AAA5-00401C608500}';
if (typeof oClientCaps != 'undefined') {
var v = oClientCaps.getComponentVersion(clsid, "ComponentID");
if ((v == '') || (v == '5,0,5000,0')) {
return false;
} else {
return true;
}
} else {
return false;
}
},
testUsingMimeTypes: function (version) {
if (!navigator.mimeTypes) {
if (deployJava.debug) {
alert('Browser claims to be Netscape family, but no mimeTypes[] array?');
}
return false;
}
for (var i = 0; i < navigator.mimeTypes.length; ++i) {
s = navigator.mimeTypes[i].type;
var m = s.match(/^application\/x-java-applet\x3Bversion=(1\.8|1\.7|1\.6|1\.5|1\.4\.2)$/);
if (m != null) {
if (deployJava.compareVersions(m[1], version)) {
return true;
}
}
}
return false;
},
testUsingPluginsArray: function (version) {
if ((!navigator.plugins) || (!navigator.plugins.length)) {
return false;
}
var platform = navigator.platform.toLowerCase();
for (var i = 0; i < navigator.plugins.length; ++i) {
s = navigator.plugins[i].description;
if (s.search(/^Java Switchable Plug-in (Cocoa)/) != -1) {
if (deployJava.compareVersions("1.5.0", version)) {
return true;
}
} else if (s.search(/^Java/) != -1) {
if (platform.indexOf('win') != -1) {
if (deployJava.compareVersions("1.5.0", version) || deployJava.compareVersions("1.6.0", version)) {
return true;
}
}
}
}
if (deployJava.compareVersions("1.5.0", version)) {
return true;
}
return false;
},
compareVersions: function (installed, required) {
var a = installed.split('.');
var b = required.split('.');
for (var i = 0; i < a.length; ++i) {
a[i] = Number(a[i]);
}
for (var i = 0; i < b.length; ++i) {
b[i] = Number(b[i]);
}
if (a.length == 2) {
a[2] = 0;
}
if (a[0] > b[0]) return true;
if (a[0] < b[0]) return false;
if (a[1] > b[1]) return true;
if (a[1] < b[1]) return false;
if (a[2] > b[2]) return true;
if (a[2] < b[2]) return false;
return true;
},
enableAlerts: function () {
deployJava.browserName = null;
deployJava.debug = true;
},
writePluginTag: function () {
var browser = deployJava.getBrowser();
if (browser == 'MSIE') {
document.write('<' + 'object classid="clsid:CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA" ' + 'id="deployJavaPlugin" width="0" height="0">' + '<' + '/' + 'object' + '>');
} else if (browser == 'Netscape Family' && deployJava.allowPlugin()) {
deployJava.writeEmbedTag();
}
},
refresh: function () {
navigator.plugins.refresh(false);
var browser = deployJava.getBrowser();
if (browser == 'Netscape Family' && deployJava.allowPlugin()) {
var plugin = document.getElementById('deployJavaPlugin');
if (plugin == null) {
deployJava.writeEmbedTag();
}
}
},
writeEmbedTag: function () {
var written = false;
if (navigator.mimeTypes != null) {
for (var i = 0; i < navigator.mimeTypes.length; i++) {
if (navigator.mimeTypes[i].type == deployJava.mimeType) {
if (navigator.mimeTypes[i].enabledPlugin) {
document.write('<' + 'embed id="deployJavaPlugin" type="' + deployJava.mimeType + '" hidden="true" />');
written = true;
}
}
}
if (!written) for (var i = 0; i < navigator.mimeTypes.length; i++) {
if (navigator.mimeTypes[i].type == deployJava.oldMimeType) {
if (navigator.mimeTypes[i].enabledPlugin) {
document.write('<' + 'embed id="deployJavaPlugin" type="' + deployJava.oldMimeType + '" hidden="true" />');
}
}
}
}
},
do_initialize: function () {
deployJava.writePluginTag();
if (deployJava.locale == null) {
var loc = null;
if (loc == null) try {
loc = navigator.userLanguage;
} catch (err) {}
if (loc == null) try {
loc = navigator.systemLanguage;
} catch (err) {}
if (loc == null) try {
loc = navigator.language;
} catch (err) {}
if (loc != null) {
loc.replace("-", "_")
deployJava.locale = loc;
}
}
}
};
deployJava.do_initialize();
But I've read regarding this code:
...if you have both a Sun JRE and
MSJVM installed, the toolkit will
report the Sun JRE version even if
it's disabled and the browser will
actually run MSJVM...
The second problem with that code is that it retrieves a list of the installed JREs, and I only care about the one that will open the Applet I need to deploy inside the browser.
Does someone knows a pure js method to get the version of Java that would run in the browser if I try load an Applet?

Categories