I am working on a project in which I have used angularjs and mvc.I am getting my status details data by http post.Now I want to use my this data in my another function of controller.I have passed my data in a scope variable $scope.Statuses and tried to use this scope variable to get data in my another function but its getting null value.Please suggest how to achieve this.
angularjs controller
var myIssuesController = function ($scope, $sce, $http, cfpLoadingBar, deviceDetector, $filter, $modal, $log) {
$("#navMyIssues").addClass("active");
$scope.issueCommnets = null;
$scope.showComments = false;
$scope.Issues = [];
$scope.dateFormat = 'dd-MMM-yyyy';
$scope.dateTimeFormat = 'dd-MMM-yyyy h:mm:ss a';
$scope.selectedIssue = null;
$scope.statusName = null;
$scope.ProjectDetails = [];
$scope.selectedProject = null;
$scope.isVisible = false;
$scope.isVisibleReply = false;
$scope.notifiedMembers = null;
$scope.defaultProfileImagePath = "";
$scope.pendingIssueCount = 0;
$scope.inprogressIssueCount = 0;
$scope.limitationIssueCount = 0;
$scope.needsresearchIssueCount = 0;
$scope.intestingIssueCount = 0;
$scope.Statuses = null;
$scope.issuesLoaded = false;
$scope.issueDetailsLoaded = false;
$scope.modalHeader;
$scope.options;
var selectedTab;
//get all assigned issues
$scope.GetAssignedIssues = function () {
//$scope.issueCount = -1;
$scope.issuesLoaded = false;
$scope.issueDetailsLoaded = false;
$scope.query = "";
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetAllAssignedIssues/';
$http.post(url, []).success(function (data, status, headers, config) {
if (data != '' || data.length == 0) {
$scope.Issues = data;
$scope.Issues = $filter('orderBy')($scope.Issues, 'CreatedOn', true);
$scope.Statuses=$scope.getIssueStatusDetails($scope.Issues[0]);
for (var count = 0; count < $scope.Issues.length; count++) {
if ($scope.Issues[count].StatusName == "Pending") {
$scope.pendingIssueCount = $scope.pendingIssueCount + 1;
}
else if ($scope.Issues[count].StatusName == "In Progress") {
$scope.inprogressIssueCount = $scope.inprogressIssueCount + 1;
}
else if ($scope.Issues[count].StatusName == "Limitation") {
$scope.limitationIssueCount = $scope.limitationIssueCount + 1;
}
else if ($scope.Issues[count].StatusName == "Needs Research") {
$scope.needsresearchIssueCount = $scope.needsresearchIssueCount + 1;
}
else if ($scope.Issues[count].StatusName == "In Testing") {
$scope.intestingIssueCount = $scope.intestingIssueCount + 1;
}
var statusColor = "";
if ( $scope.Statuses[count]["Name"] == $scope.Issues[count].StatusName) {
statusColor = $scope.Statuses[count]["ColorInHexa"];
$scope.Issues[count].IssueStatusStyle = "border-bottom: 4px solid " + statusColor + " !important;padding-bottom: 5px;";
}
}
if (data.length != 0) {
if ($scope.selectedIssue == null) {
$scope.selectedIssue = $scope.Issues[0];
} else {
for (var count = 0; count < $scope.Issues.length;count++)
{
if($scope.Issues[count].Id==$scope.selectedIssue.Id) {
$scope.selectedIssue = $scope.Issues[count];
}
}
}
}
$scope.issuesLoaded = true;
$scope.showIssueDetails($scope.selectedIssue);
}
else {
$scope.errors.push(data.error);
//$scope.issueCount = -1;
}
if ($scope.isVisible == false) {
$("#changedetailsbox").hide();
$scope.isVisible = true;
}
if ($scope.isVisibleReply == false) {
$("#postReplybox").hide();
$scope.isVisibleReply = true;
}
}
);
};
$scope.GetAssignedIssues();
$scope.getIssueStatusDetails = function (issue) {
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetIssueStatusDetails/';
$http.post(url, { ProjectId: issue.ProjectId } ).success(function(data, status, headers, config) {
if (data != '' || data.length != 0) {
$scope.selectedProject = data;
$scope.Statuses = $scope.selectedProject.Statuses;
} else {
$scope.errors.push(data.error);
}
});
};
}
AngularJS Services is your best friend when you need access variables or functions between controllers. Most commonly used services are: 'factory', 'provider', 'service'
"Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app."
More information on AngularJS website
https://docs.angularjs.org/guide/services
Better explanation:
AngularJS: Service vs provider vs factory
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>
i made a module for odoo 12 to lock the pos screen the code works fine in odoo 10, but gives error this.pos is null or this.pos.currency is undefined. in the models.js, i want to switch the orders of different cashiers but this.pos is not initialized, what should i do so that it becomes initialized?
here is my code:
odoo.define('pos_user_lock.models',
//['point_of_sale.models','point_of_sale.screens','point_of_sale.chrome'
//,'web.ajax','web.core'],
function (require) {
"use strict";
var ajax = require('web.ajax');
var screens = require('point_of_sale.screens');
var models = require('point_of_sale.models');
var chrome = require('point_of_sale.chrome');
var core = require('web.core');
var QWeb = core.qweb;
var _t = core._t;
models.Order = models.Order.extend({
initialize: function(attributes,options){
var order = models.Order.__super__.initialize.call(this,attributes,options);
if (!this.cashier)
{
this.cashier = this.pos.cashier || this.pos.user;
}
this.is_last_selected = (this.is_last_selected === undefined) ? false:this.is_last_selected;
return order;
},
finalize: function() {
var res = models.Order.__super__.finalize.call(this);
this.pos.lock_user_screen();
},
init_from_JSON: function(json) {
var user = this.get_user_by_id(json.user_id);
if (user)
this.cashier = user;
this.is_last_selected = json.is_last_selected;
models.Order.__super__.init_from_JSON.call(this, json);
},
export_as_JSON: function() {
var res = models.Order.__super__.export_as_JSON.call(this);
if (this.cashier)
res.user_id = this.cashier.id ;
if(this.pos && this.pos.get_cashier())
res.user_id = this.pos.get_cashier().id ;
res.is_last_selected = this.is_last_selected;
return res;
},
get_user_by_id: function(id) {
var users = this.pos.users;
for (var i = 0; i < users.length; i++) {
var user = users[i];
if (user.id == id)
return user;
}
},
});
models.PosModel = models.PosModel.extend({
initialize: function(session, attributes) {
models.PosModel.__super__.initialize.call(this, session, attributes);
var self = this;
alert(JSON.stringify(attributes.pos));
this.ready.then(function(){
if (self.config.auto_push_order)
self.config.iface_precompute_cash = true;
});
},
is_locked: function(){
if (
this.gui.current_popup
&& this.gui.current_popup.template == 'PasswordPinPopupWidget'
){
return true;
}
return false;
},
unlock: function(){
if (this.is_locked()){
this.gui.close_popup();
}
},
lock_user_screen: function(){
var self = this;
if (!this.config.lock_users) return;
this.gui.show_popup('passwordPin',{
'title': _t('Insert password or scan your barcode'),
});
},
get_last_order: function(){
var orders = this.get_order_list();
for (var i = 0; i < orders.length; i++) {
if (orders[i].is_last_selected) {
return orders[i];
}
}
return null;
},
set_last_order: function(order){
var orders = this.get_order_list();
for (var i = 0; i < orders.length; i++) {
if (orders[i].uid == order.uid) {
orders[i].is_last_selected = true;
}else{
orders[i].is_last_selected = false;
}
}
return null;
},
set_order: function(order){
models.PosModel.__super__.set_order.call(this, order);
this.set_last_order(order);
},
get_order_list: function(){
var orders = models.PosModel.__super__.get_order_list.call(this);
var c_orders = [];
var cashier = this.cashier || this.user;
for (var i = 0; i < orders.length; i++) {
if (cashier && orders[i].cashier.id === cashier.id) {
c_orders.push(orders[i]);
}
}
return c_orders;
},
switch_order: function(){
var self = this;
if(self.pos)
{
}
else
{
alert("self.pos is null");
}
if(self !== undefined && self != null && self.pos !== undefined && self.pos.currency != null)
{
alert("in switch order");
//console.log(this.pos.currency);
if (!self.config.lock_users) return;
var user = self.pos.get_cashier() || self.user;
var orders = self.get_order_list();
var last_order = self.get_last_order() || orders[0];
if (orders.length) {
self.set_order(last_order);
}
else {
self.add_new_order();
}
}
},
set_cashier: function(user){
models.PosModel.__super__.set_cashier.call(this,user);
if(this.pos)
{
alert("this.pos is not null in set_cashier");
}
else
{
alert("this.pos is null in set_cashier");
}
this.switch_order(this);
if (!this.table && this.config.iface_floorplan)
this.set_table(null);
},
});
return models;
});
the web page shows this.pos is null. and this.currency is null.
i found the solution by adding:
this.pos = this;
inside initialize function of PosModel.
I was using ng-repeat directive to show a huge list in my ionic app and recently switched to collection-repeat. However with collection repeat list got pretty short and it does not show all the array items. In code I only change collection-repeat to ng-repeat and it works just as expected. Btw I am trying to use it in a directive definition which is angucomplete and in directive I customly filter data here is the relevant html and js:
'<div class="angucomplete-holder">'+
'<input id="{{id}}_value" ng-model="searchStr" type="text" placeholder="{{placeholder}}" class="{{inputClass}}" onmouseup="this.select();" ng-focus="resetHideResults()" />'+
'<ion-scroll direction="y" id="{{id}}_dropdown" class="angucomplete-dropdown" ng-if="showDropdown">'+
'<div class="angucomplete-searching" ng-show="searching">Searching...</div>'+
'<div class="angucomplete-searching" ng-show="!searching && (!results || results.length == 0)">No results found</div>'+
'<div class="angucomplete-searching" ng-show="!searching && (!results || results.length == 0)">{{noResultMsg}}</div>'+
'<div class="angucomplete-searching" ng-show="!searching && (!results || results.length == 0)"><img src="img/title_icon.png" style="width:30px;height:30px;"/></div>'+
'<div class="angucomplete-row" collection-repeat="result in results track by $index" ng-mousedown="selectResult(result)" ng-class="{\'angucomplete-selected-row\': $index == currentIndex}">'+
'<div ng-if="imageField" class="angucomplete-image-holder">'+
'<img ng-if="result.image && result.image != \'\'" ng-src="{{result.image}}" class="angucomplete-image"/>'+
'<div ng-if="!result.image && result.image != \'\'" class="angucomplete-image-default"></div>'+
'</div>'+
'<div class="angucomplete-title" ng-if="matchClass" ng-bind-html="result.title"></div>'+
'<div class="angucomplete-title" ng-if="!matchClass">{{ result.title }}</div>'+
'<div ng-if="result.description && result.description != \'\'" class="angucomplete-description">{{result.description}}</div>'+
'</div>'+
'</ion-scroll>'+
'</div>',
and here is the js:
isNewSearchNeeded = function(newTerm, oldTerm) {
return newTerm.length >= $scope.minLength && newTerm != oldTerm
}
$scope.processResults = function(responseData, str) {
if (responseData && responseData.length > 0) {
$scope.results = [];
var titleFields = [];
if ($scope.titleField && $scope.titleField != "") {
titleFields = $scope.titleField.split(",");
}
for (var i = 0; i < responseData.length; i++) {
// Get title variables
var titleCode = [];
for (var t = 0; t < titleFields.length; t++) {
titleCode.push(responseData[i][titleFields[t]]);
}
var description = "";
if ($scope.descriptionField) {
description = responseData[i][$scope.descriptionField];
}
var imageUri = "";
if ($scope.imageUri) {
imageUri = $scope.imageUri;
}
var image = "";
if ($scope.imageField) {
image = imageUri + responseData[i][$scope.imageField];
}
var text = titleCode.join(' ');
if ($scope.matchClass) {
var re = new RegExp(str, 'i');
var strPart = text.match(re)[0];
text = $sce.trustAsHtml(text.replace(re, '<span class="'+ $scope.matchClass +'">'+ strPart +'</span>'));
}
var resultRow = {
title: text,
description: description,
image: image,
originalObject: responseData[i]
}
$scope.results[$scope.results.length] = resultRow;
}
} else {
$scope.results = [];
}
}
$scope.searchTimerComplete = function(str) {
// Begin the search
if (str.length >= $scope.minLength) {
if ($scope.localData) {
var searchFields = $scope.searchFields.split(",");
var matches = [];
for (var i = 0; i < $scope.localData.length; i++) {
var match = false;
for (var s = 0; s < searchFields.length; s++) {
match = match || (typeof $scope.localData[i][searchFields[s]] === 'string' && typeof str === 'string' && $scope.localData[i][searchFields[s]].toLowerCase().indexOf(str.toLowerCase()) >= 0);
}
if (match) {
matches[matches.length] = $scope.localData[i];
}
}
$scope.searching = false;
$scope.processResults(matches, str);
} else {
$http.get($scope.url + str, {}).
success(function(responseData, status, headers, config) {
$scope.searching = false;
$scope.processResults((($scope.dataField) ? responseData[$scope.dataField] : responseData ), str);
}).
error(function(data, status, headers, config) {
console.log("error");
});
}
}
}
$scope.hideResults = function() {
$scope.hideTimer = $timeout(function() {
$scope.showDropdown = false;
}, $scope.pause);
};
$scope.resetHideResults = function() {
if($scope.hideTimer) {
$timeout.cancel($scope.hideTimer);
};
};
$scope.hoverRow = function(index) {
$scope.currentIndex = index;
}
$scope.keyPressed = function(event) {
if (!(event.which == 38 || event.which == 40 || event.which == 13)) {
if (!$scope.searchStr || $scope.searchStr == "") {
$scope.showDropdown = false;
$scope.lastSearchTerm = null
} else if (isNewSearchNeeded($scope.searchStr, $scope.lastSearchTerm)) {
$scope.lastSearchTerm = $scope.searchStr
$scope.showDropdown = true;
$scope.currentIndex = -1;
$scope.results = [];
if ($scope.searchTimer) {
$timeout.cancel($scope.searchTimer);
}
$scope.searching = true;
$scope.searchTimer = $timeout(function() {
$scope.searchTimerComplete($scope.searchStr);
}, $scope.pause);
}
} else {
event.preventDefault();
}
}
$scope.selectResult = function(result) {
if ($scope.matchClass) {
result.title = result.title.toString().replace(/(<([^>]+)>)/ig, '');
}
$scope.searchStr = $scope.lastSearchTerm = result.title;
$scope.selectedObject = result.title;
$scope.showDropdown = false;
$scope.results = [];
//$scope.$apply();
}
var inputField = elem.find('input');
inputField.on('keyup', $scope.keyPressed);
elem.on("keyup", function (event) {
if(event.which === 40) {
if ($scope.results && ($scope.currentIndex + 1) < $scope.results.length) {
$scope.currentIndex ++;
$scope.$apply();
event.preventDefault;
event.stopPropagation();
}
$scope.$apply();
} else if(event.which == 38) {
if ($scope.currentIndex >= 1) {
$scope.currentIndex --;
$scope.$apply();
event.preventDefault;
event.stopPropagation();
}
} else if (event.which == 13) {
if ($scope.results && $scope.currentIndex >= 0 && $scope.currentIndex < $scope.results.length) {
$scope.selectResult($scope.results[$scope.currentIndex]);
$scope.$apply();
event.preventDefault;
event.stopPropagation();
} else {
$scope.results = [];
$scope.$apply();
event.preventDefault;
event.stopPropagation();
}
} else if (event.which == 27) {
$scope.results = [];
$scope.showDropdown = false;
$scope.$apply();
} else if (event.which == 8) {
$scope.selectedObject = null;
$scope.$apply();
}
});
Any help would be appreciated. Thanks...
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?