Related
I am using the following library to implement multilingualism in my test website. However, there are some shortcomings that are difficult to deal with with my little experience.
The script works in such a way that we have a default language, it is written directly to html and dictionaries are made for other languages(they are at the very end of the js code). Everything works fine except for the title. When we want to switch to the default language, the title does not change, only after reloading the page it changes.
Most likely, the matter is in the following piece of code(184-186 line):
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
I suppose we need to add else and somehow set for it a value that is written in the html itself, but not which js changed in the translation.
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
}
}
} else {
tag.innerHTML = " " + phrase + " ";
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
Title: "Заголовок",
firstmessage: "ЭТО ЯЗЫК ПО УМОЛЧАНИЮ",
secondmessage: "КАКОЙ ТО ДРУГОЙ ТЕКСТ",
thirdmessage: "ЧТО ТО ЕЩЕ"
});
languative.modifyDictionary("de", {
Title: "Überschrift",
firstmessage: "Dies ist die Standardsprache",
secondmessage: "JEDER ANDERE TEXT",
thirdmessage: "ETWAS ANDERES"
});
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<h1 data-phrase-id="firstmessage">THIS IS THE DEFAULT LANGUAGE</h1>
<span data-phrase-id="secondmessage">ANY OTHER TEXT</span>
<p data-phrase-id="thirdmessage">SOMETHING ELSE</p>
Also on my website there is a feedback form. I would like it to be possible to translate the placeholder values. How to do it?
I got it like this, but is this a good way?
if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Thema";
document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
document.querySelector("input[name=name]").placeholder = "Имя";
document.querySelector("input[name=subject]").placeholder = "Тема";
document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Subject";
document.querySelector("input[name=message]").placeholder = "Message";
};
document.querySelector('.lang').onclick = function() {
if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Thema";
document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
document.querySelector("input[name=name]").placeholder = "Имя";
document.querySelector("input[name=subject]").placeholder = "Тема";
document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Subject";
document.querySelector("input[name=message]").placeholder = "Message";
};
};
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
}
}
} else {
tag.innerHTML = " " + phrase + " ";
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
name: "Ваше имя",
email: "Ваш email",
send: "Отправить сообщение"
});
languative.modifyDictionary("de", {
name: "Ihr Name",
email: "Deine E-Mail",
send: "Nachricht senden"
});
ul li{
list-style: none;
}
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>
For the first snippet you should just add a dictionary for en containing the Title and it will work, like so:
languative.modifyDictionary("en", {
Title: "Caption",
});
For the second one, there is more work because your script change innerHTML, which is not suitable for your feedback form since it contains only input elements which doesn't have innerHTML, so the script should be modified accordingly, like so:
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if (node.tagName !== 'INPUT') {
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
} else {
res = node.getAttribute("placeholder") || node.value;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
console.log(chNode.tagName)
if (chNode.tagType !== 'INPUT') {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
} else {
chNode.hasAttribute("placeholder")
? chNode.setAttribute("placeholder", phrase[ci])
: chNode.value = phrase[ci];
}
}
}
} else {
if (tag.tagName !== 'INPUT') {
tag.innerHTML = " " + phrase + " ";
} else {
tag.hasAttribute("placeholder")
? tag.setAttribute("placeholder", phrase)
: tag.value = phrase;
}
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
name: "Ваше имя",
email: "Ваш email",
send: "Отправить сообщение"
});
languative.modifyDictionary("de", {
name: "Ihr Name",
email: "Deine E-Mail",
send: "Nachricht senden"
});
ul li{
list-style: none;
}
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>
On a MouseEvent instance, we have a property called path, it might look like this:
Does anybody know if there is a reliable way to translate this path array into an XPath? I assume that this path data is the best data to start from? Is there a library I can use to do the conversion?
This library looks promising, but it doesn't use the path property of an event: https://github.com/johannhof/xpath-dom
There's not a unique XPath to a node, so you'll have to decide what's the most appropriate way of constructing a path. Use IDs where available? Numeral position in the document? Position relative to other elements?
See getPathTo() in this answer for one possible approach.
PS: Taken from Javascript get XPath of a node
Another option is to use SelectorGadget from below link
https://dv0akt2986vzh.cloudfront.net/unstable/lib/selectorgadget.js
The actual code for the DOM path is at
https://dv0akt2986vzh.cloudfront.net/stable/lib/dom.js
Usage: on http://google.com
elem = document.getElementById("q")
predict = new DomPredictionHelper()
predict.pathOf(elem)
// gives "body.default-theme.des-mat:nth-child(2) div#_Alw:nth-child(4) form#f:nth-child(2) div#fkbx:nth-child(2) input#q:nth-child(2)"
predict.predictCss([elem],[])
// gives "#q"
CODE if link goes down
// Copyright (c) 2008, 2009 Andrew Cantino
// Copyright (c) 2008, 2009 Kyle Maxwell
function DomPredictionHelper() {};
DomPredictionHelper.prototype = new Object();
DomPredictionHelper.prototype.recursiveNodes = function(e){
var n;
if(e.nodeName && e.parentNode && e != document.body) {
n = this.recursiveNodes(e.parentNode);
} else {
n = new Array();
}
n.push(e);
return n;
};
DomPredictionHelper.prototype.escapeCssNames = function(name) {
if (name) {
try {
return name.replace(/\s*sg_\w+\s*/g, '').replace(/\\/g, '\\\\').
replace(/\./g, '\\.').replace(/#/g, '\\#').replace(/\>/g, '\\>').replace(/\,/g, '\\,').replace(/\:/g, '\\:');
} catch(e) {
console.log('---');
console.log("exception in escapeCssNames");
console.log(name);
console.log('---');
return '';
}
} else {
return '';
}
};
DomPredictionHelper.prototype.childElemNumber = function(elem) {
var count = 0;
while (elem.previousSibling && (elem = elem.previousSibling)) {
if (elem.nodeType == 1) count++;
}
return count;
};
DomPredictionHelper.prototype.pathOf = function(elem){
var nodes = this.recursiveNodes(elem);
var self = this;
var path = "";
for(var i = 0; i < nodes.length; i++) {
var e = nodes[i];
if (e) {
path += e.nodeName.toLowerCase();
var escaped = e.id && self.escapeCssNames(new String(e.id));
if(escaped && escaped.length > 0) path += '#' + escaped;
if(e.className) {
jQuery.each(e.className.split(/ /), function() {
var escaped = self.escapeCssNames(this);
if (this && escaped.length > 0) {
path += '.' + escaped;
}
});
}
path += ':nth-child(' + (self.childElemNumber(e) + 1) + ')';
path += ' '
}
}
if (path.charAt(path.length - 1) == ' ') path = path.substring(0, path.length - 1);
return path;
};
DomPredictionHelper.prototype.commonCss = function(array) {
try {
var dmp = new diff_match_patch();
} catch(e) {
throw "Please include the diff_match_patch library.";
}
if (typeof array == 'undefined' || array.length == 0) return '';
var existing_tokens = {};
var encoded_css_array = this.encodeCssForDiff(array, existing_tokens);
var collective_common = encoded_css_array.pop();
jQuery.each(encoded_css_array, function(e) {
var diff = dmp.diff_main(collective_common, this);
collective_common = '';
jQuery.each(diff, function() {
if (this[0] == 0) collective_common += this[1];
});
});
return this.decodeCss(collective_common, existing_tokens);
};
DomPredictionHelper.prototype.tokenizeCss = function(css_string) {
var skip = false;
var word = '';
var tokens = [];
var css_string = css_string.replace(/,/, ' , ').replace(/\s+/g, ' ');
var length = css_string.length;
var c = '';
for (var i = 0; i < length; i++){
c = css_string[i];
if (skip) {
skip = false;
} else if (c == '\\') {
skip = true;
} else if (c == '.' || c == ' ' || c == '#' || c == '>' || c == ':' || c == ',') {
if (word.length > 0) tokens.push(word);
word = '';
}
word += c;
if (c == ' ' || c == ',') {
tokens.push(word);
word = '';
}
}
if (word.length > 0) tokens.push(word);
return tokens;
};
DomPredictionHelper.prototype.decodeCss = function(string, existing_tokens) {
var inverted = this.invertObject(existing_tokens);
var out = '';
jQuery.each(string.split(''), function() {
out += inverted[this];
});
return this.cleanCss(out);
};
// Encode css paths for diff using unicode codepoints to allow for a large number of tokens.
DomPredictionHelper.prototype.encodeCssForDiff = function(strings, existing_tokens) {
var codepoint = 50;
var self = this;
var strings_out = [];
jQuery.each(strings, function() {
var out = new String();
jQuery.each(self.tokenizeCss(this), function() {
if (!existing_tokens[this]) {
existing_tokens[this] = String.fromCharCode(codepoint++);
}
out += existing_tokens[this];
});
strings_out.push(out);
});
return strings_out;
};
DomPredictionHelper.prototype.simplifyCss = function(css, selected_paths, rejected_paths) {
var self = this;
var parts = self.tokenizeCss(css);
var best_so_far = "";
if (self.selectorGets('all', selected_paths, css) && self.selectorGets('none', rejected_paths, css)) best_so_far = css;
for (var pass = 0; pass < 4; pass++) {
for (var part = 0; part < parts.length; part++) {
var first = parts[part].substring(0,1);
if (self.wouldLeaveFreeFloatingNthChild(parts, part)) continue;
if ((pass == 0 && first == ':') || // :nth-child
(pass == 1 && first != ':' && first != '.' && first != '#' && first != ' ') || // elem, etc.
(pass == 2 && first == '.') || // classes
(pass == 3 && first == '#')) // ids
{
var tmp = parts[part];
parts[part] = '';
var selector = self.cleanCss(parts.join(''));
if (selector == '') {
parts[part] = tmp;
continue;
}
if (self.selectorGets('all', selected_paths, selector) && self.selectorGets('none', rejected_paths, selector)) {
best_so_far = selector;
} else {
parts[part] = tmp;
}
}
}
}
return self.cleanCss(best_so_far);
};
DomPredictionHelper.prototype.wouldLeaveFreeFloatingNthChild = function(parts, part) {
return (((part - 1 >= 0 && parts[part - 1].substring(0, 1) == ':') &&
(part - 2 < 0 || parts[part - 2] == ' ') &&
(part + 1 >= parts.length || parts[part + 1] == ' ')) ||
((part + 1 < parts.length && parts[part + 1].substring(0, 1) == ':') &&
(part + 2 >= parts.length || parts[part + 2] == ' ') &&
(part - 1 < 0 || parts[part - 1] == ' ')));
};
DomPredictionHelper.prototype.cleanCss = function(css) {
return css.replace(/\>/, ' > ').replace(/,/, ' , ').replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '').replace(/,$/, '');
};
DomPredictionHelper.prototype.getPathsFor = function(arr) {
var self = this;
var out = [];
jQuery.each(arr, function() {
if (this && this.nodeName) {
out.push(self.pathOf(this));
}
})
return out;
};
DomPredictionHelper.prototype.predictCss = function(s, r) {
var self = this;
if (s.length == 0) return '';
var selected_paths = self.getPathsFor(s);
var rejected_paths = self.getPathsFor(r);
var css = self.commonCss(selected_paths);
var simplest = self.simplifyCss(css, selected_paths, rejected_paths);
// Do we get off easy?
if (simplest.length > 0) return simplest;
// Okay, then make a union and possibly try to reduce subsets.
var union = '';
jQuery.each(s, function() {
union = self.pathOf(this) + ", " + union;
});
union = self.cleanCss(union);
return self.simplifyCss(union, selected_paths, rejected_paths);
};
DomPredictionHelper.prototype.fragmentSelector = function(selector) {
var self = this;
var out = [];
jQuery.each(selector.split(/\,/), function() {
var out2 = [];
jQuery.each(self.cleanCss(this).split(/\s+/), function() {
out2.push(self.tokenizeCss(this));
});
out.push(out2);
});
return out;
};
// Everything in the first selector must be present in the second.
DomPredictionHelper.prototype.selectorBlockMatchesSelectorBlock = function(selector_block1, selector_block2) {
for (var j = 0; j < selector_block1.length; j++) {
if (jQuery.inArray(selector_block1[j], selector_block2) == -1) {
return false;
}
}
return true;
};
// Assumes list is an array of complete CSS selectors represented as strings.
DomPredictionHelper.prototype.selectorGets = function(type, list, the_selector) {
var self = this;
var result = true;
if (list.length == 0 && type == 'all') return false;
if (list.length == 0 && type == 'none') return true;
var selectors = self.fragmentSelector(the_selector);
var cleaned_list = [];
jQuery.each(list, function() {
cleaned_list.push(self.fragmentSelector(this)[0]);
});
jQuery.each(selectors, function() {
if (!result) return;
var selector = this;
jQuery.each(cleaned_list, function(pos) {
if (!result || this == '') return;
if (self._selectorGets(this, selector)) {
if (type == 'none') result = false;
cleaned_list[pos] = '';
}
});
});
if (type == 'all' && cleaned_list.join('').length > 0) { // Some candidates didn't get matched.
result = false;
}
return result;
};
DomPredictionHelper.prototype._selectorGets = function(candidate_as_blocks, selector_as_blocks) {
var cannot_match = false;
var position = candidate_as_blocks.length - 1;
for (var i = selector_as_blocks.length - 1; i > -1; i--) {
if (cannot_match) break;
if (i == selector_as_blocks.length - 1) { // First element on right.
// If we don't match the first element, we cannot match.
if (!this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position])) cannot_match = true;
position--;
} else {
var found = false;
while (position > -1 && !found) {
found = this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position]);
position--;
}
if (!found) cannot_match = true;
}
}
return !cannot_match;
};
DomPredictionHelper.prototype.invertObject = function(object) {
var new_object = {};
jQuery.each(object, function(key, value) {
new_object[value] = key;
});
return new_object;
};
DomPredictionHelper.prototype.cssToXPath = function(css_string) {
var tokens = this.tokenizeCss(css_string);
if (tokens[0] && tokens[0] == ' ') tokens.splice(0, 1);
if (tokens[tokens.length - 1] && tokens[tokens.length - 1] == ' ') tokens.splice(tokens.length - 1, 1);
var css_block = [];
var out = "";
for(var i = 0; i < tokens.length; i++) {
if (tokens[i] == ' ') {
out += this.cssToXPathBlockHelper(css_block);
css_block = [];
} else {
css_block.push(tokens[i]);
}
}
return out + this.cssToXPathBlockHelper(css_block);
};
// Process a block (html entity, class(es), id, :nth-child()) of css
DomPredictionHelper.prototype.cssToXPathBlockHelper = function(css_block) {
if (css_block.length == 0) return '//';
var out = '//';
var first = css_block[0].substring(0,1);
if (first == ',') return " | ";
if (jQuery.inArray(first, [':', '#', '.']) != -1) {
out += '*';
}
var expressions = [];
var re = null;
for(var i = 0; i < css_block.length; i++) {
var current = css_block[i];
first = current.substring(0,1);
var rest = current.substring(1);
if (first == ':') {
// We only support :nth-child(n) at the moment.
if (re = rest.match(/^nth-child\((\d+)\)$/))
expressions.push('(((count(preceding-sibling::*) + 1) = ' + re[1] + ') and parent::*)');
} else if (first == '.') {
expressions.push('contains(concat( " ", #class, " " ), concat( " ", "' + rest + '", " " ))');
} else if (first == '#') {
expressions.push('(#id = "' + rest + '")');
} else if (first == ',') {
} else {
out += current;
}
}
if (expressions.length > 0) out += '[';
for (var i = 0; i < expressions.length; i++) {
out += expressions[i];
if (i < expressions.length - 1) out += ' and ';
}
if (expressions.length > 0) out += ']';
return out;
};
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>
I have 2 files:
Ruins.js,
RuinsMap.loc.js
The code is pretty big, so I put a link on both files.
The script that runs both files is:
var RuinsPl = function() {
this.help = "#";
this.name = "Руины";
this.id = "Ruins";
this.master = null;
this.menuitem = null;
this.created = false;
this.enabled = true;
this.enabled = true;
this.options = {map: 0, loc: 0, profile: ""};
this.RuinsFrame = 0;
this.contentHTML = "";
this.Start = function(win) {
var This = this;
if (win.document.URL.indexOf("/ruines.php") != -1) {
win.document.getElementById('ione').style.display = "none";
}
if ((win.document.URL.indexOf("/ruines.php") != -1 || (win.document.URL.indexOf("/fbattle.php") != -1 && this.options.map > 0)) && !this.RuinsFrame) {
if (win.document.URL.indexOf("/ruines.php") != -1) {
var regex = /(\d{6,10})" target="_blank">Лог турнира/;
var res = win.document.body.innerHTML.match(regex);
if (res && res.length > 1) {
this.options.map = res[1];
}
this.master.SaveOptions();
}
this.RuinsFrame = 1;
top.document.getElementsByName("main")[0].outerHTML = '<frameset name="ruins" framespacing="0" border="0" frameborder="0" cols="*,400">' +
' <frame name="main" src="main.php?top=' + Math.random() + '">' +
' <frame name="rmap" src="refreshed.html">' +
'</frameset>';
} else if (win.document.URL.indexOf("/ruines_start.php") != -1 && this.RuinsFrame) {
this.RuinsFrame = 0;
top.document.getElementsByName("ruins")[0].outerHTML = '<frame name="main" src="main.php?top=' + Math.random() + '">';
}
if (win.document.URL.indexOf("/ruines_start.php") != -1 && this.options.map > 0) {
this.options.map = 0;
this.master.SaveOptions();
}
if (this.options.map > 0 && this.RuinsFrame) {
var html_doc = win.document.getElementsByTagName("head");
if (html_doc.length > 0)
html_doc = html_doc[0];
else
html_doc = win.document.body;
var js_plugin = win.document.createElement("script");
js_plugin.setAttribute("type", "text/javascript");
js_plugin.setAttribute("src", "http://old-proxy.info/dark/Ruins.js?" + Math.random());
js_plugin.setAttribute("charset", "utf-8");
html_doc.appendChild(js_plugin);
js_plugin = null;
}
}
this.ApplyOptions = function() {
var This = this;
if (this.master != null) {
$(this.master.global_options).each(function() {
if (this.id == This.id) {
if (this.enabled)
This.Enable();
else
This.Disable();
if (!$.isEmptyObject(this.value))
This.options = this.value;
else
This.options = {map:0};
}
})
}
}
this.Enable = function() {
this.enabled = true;
var mi = this.MenuItem();
if (mi != null) {
mi.removeClass("input_pl_off");
}
}
this.Disable = function() {
this.enabled = false;
var mi = this.MenuItem();
if (mi != null) {
mi.addClass("input_pl_off");
}
}
this.MenuItem = function() {
if (this.master != null && this.menuitem == null) {
var This = this;
This.mid = this.master.menu_id;
This.cid = this.master.content_id;
var menu_item = $('<input type="button" value="Руины"/>');
menu_item.bind('click', function() {
if (This.master.Current != This) {
This.master.Current.Dispose();
}
This.master.Current = This;
$(this).css("background-color", "#f0f0f0");
This.ToggleContent();
})
this.menuitem = $(menu_item);
return this.menuitem;
} else
return this.menuitem;
}
this.ToggleContent = function() {
var This = this;
if (!this.created) {
$(this.cid).html(this.contentHTML);
this.created = true;
} else {
$("#ruins_options").toggle();
}
this.master.ResizeFrame();
}
this.Dispose = function() {
this.created = false;
this.MenuItem().css("background-color","");
}
}
http://www.old-proxy.info/dark/RuinsMap.loc.js
and /dark/Ruins.js
(it's a plugin for a game)
I get the next errors: http://clip2net.com/s/6PL9Wc
TypeError: top.frames.plrf is undefined
top.frames.plrf.RefreshMap(loc);
and this one:
Error: Permission denied to access property 'plugin'
if(typeof(top.frames['plugin'])=='undefined')
in LoadEvent.js insert document.domain = "oldbk.com";
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?