I am trying to fix this script to automatically connect people you may know on Linkedin based on User roles (CEO e.t.c), Can someone help me fix this, Below is my code; I have tried the script on almost all browsers, Somebody help fix this.
var userRole = [
"CEO",
"CIO"
];
var inviter = {} || inviter;
inviter.userList = [];
inviter.className = 'button-secondary-small';
inviter.refresh = function () {
window.scrollTo(0, document.body.scrollHeight);
window.scrollTo(document.body.scrollHeight, 0);
window.scrollTo(0, document.body.scrollHeight);
};
inviter.initiate = function()
{
inviter.refresh();
var connectBtns = $(".button-secondary-small:visible");
//
if (connectBtns == null) {var connectBtns = inviter.initiate();}
return connectBtns;
};
inviter.invite = function () {
var connectBtns = inviter.initiate();
var buttonLength = connectBtns.length;
for (var i = 0; i < buttonLength; i++) {
if (connectBtns != null && connectBtns[i] != null) {inviter.handleRepeat(connectBtns[i]);}
//if there is a connect button and there is at least one that has not been pushed, repeat
if (i == buttonLength - 1) {
console.log("done: " + i);
inviter.refresh();
}
}
};
inviter.handleRepeat = function(button)
{
var nameValue = button.children[1].textContent
var name = nameValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
function hasRole(role){
for(var i = 0; i < role.length; i++) {
// cannot read children of undefined
var position = button.parentNode.parentNode.children[1].children[1].children[0].children[3].textContent;
var formatedPosition = position.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var hasRole = formatedPosition.indexOf(role[i]) == -1 ? false : true;
console.log('Has role: ' + role[i] + ' -> ' + hasRole);
if (hasRole) {
return hasRole;
}
}
return false;
}
if(inviter.arrayContains(name))
{
console.log("canceled");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (hasRole(userRole) == false) {
console.log("cancel");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (button.textContent.indexOf("Connect")<0){
console.log("skipped");
inviter.userList.push(name); // it's likely that this person didn't join linkedin in the meantime, so we'll ignore them
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else {
console.log("added");
inviter.userList.push(name);
button.click();
}
};
inviter.arrayContains = function(item)
{
return (inviter.userList.indexOf(item) > -1);
};
inviter.usersJson = {};
inviter.loadResult = function()
{
var retrievedObject = localStorage.getItem('inviterList');
var temp = JSON.stringify(retrievedObject);
inviter.userList = JSON.parse(temp);
};
inviter.saveResult = function()
{
inviter.usersJson = JSON.stringify(inviter.userList);
localStorage.setItem('inviterList', inviter.usersJson);
};
setInterval(function () { inviter.invite(); }, 5000);
`
When I try executing this, I get the following error:
VM288:49 Uncaught TypeError: Cannot read property 'children' of undefined
at hasRole (<anonymous>:49:71)
at Object.inviter.handleRepeat (<anonymous>:66:11)
at Object.inviter.invite (<anonymous>:30:69)
at <anonymous>:108:35
Any ideas as to how to fix it?
Related
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.
class Pairs extends Screen {
constructor() {
super();
var pair1 = null;
var nPair1;
var solution;
var rightCounter = 0;
var licao, nS;
}
pairScreen(screen, lesson, nScreen) {
var body = document.body
var nodes = xmlDoc.getElementsByTagName("PAIRS");
this.licao = lesson;
this.nS = nScreen;
this.solution = screen.getElementsByTagName("SOLUTION")[0].textContent.split(" ");
body.innerHTML = '';
Startup.h1(body, "Babel (" + languageName + ")");
Startup.hr(body);
var d = DynamicHTML.div(body, "border:3px solid black; display:table; padding:20px; margin-left:40px");
Startup.h1(d, "Match the pairs");
var p1 = Startup.p(d, "padding-left:40px; word-spacing:50px;");
Startup.text(p1, 16, " ");
Startup.text(p1, 32, " ");
var p2 = Startup.p(d, "padding-left:20px;");
var button;
var i;
var f = function(i) {
Startup.eventHandler2()
}
var original = screen.getElementsByTagName("ORIGINAL")[0].textContent;
var buttons = original.split(" ");
for (i = 0; i < buttons.length; i++) {
button = DynamicHTML.inpuButton(p1, i, buttons[i], "orangered");
Startup.eventHandler2(document.getElementById(i), "onclick", function() {
checkAnswer(buttons[i], i)
});
}
Startup.hr(body);
}
checkAnswer(pair, nPair) {
var index;
if (pair1 = null) {
pair1 = pair;
nPair1 = nPair;
} else {
for (index = 0; index < solution.length; index++) {
if (pair1 == solution[index]) {
if (index % 2 == 0 && solution[index - 1] == pair) {
DynamicHTML.play("general/right_answer.mp3");
rightCounter = rightCounter + 2;
document.getElementById(nPair).disabled = true;
document.getElementById(nPair1).disabled = true;
pair1 = null;
nPair1 = null;
} else if (solution[index + 1] == pair) {
DynamicHTML.play("general/right_answer.mp3");
rightCounter = rightCounter + 2;
document.getElementById(nPair).disabled = true;
document.getElementById(nPair1).disabled = true;
pair1 = null;
nPair1 = null;
} else {
DynamicHTML.play("general/wrong_answer.mp3");
pair1 = null;
nPair1 = null;
}
}
}
}
if (rightCounter == solution.length) {
if (xmlDoc.getElementsByTagName("LESSON")[licao].childNodes[nS + 2] != null) {
var fs = new Screen();
fs.functionScreen(licao, nS + 2);
} else fs.initialScreen();
}
}
}
Wrote this for a JavaScript project I'm working on but when I run it It says Uncaught ReferenceError: checkAnswer is not defined, I'd really appreciate if anyone knew the problem. Thank you!
P.S. Don't know if the checkAnswer function has bugs or note becausa I couldn't test it out, I will when I can run it :)
First you need to bind this at the end of this function:
Startup.eventHandler2(document.getElementById(i), "onclick", function() {
this.checkAnswer(buttons[i], i)
}.bind(this));
Basically this tells the anonymous function "hey I want this to refer to this outer class, not the function itself".
(edited)
You need to either bind checkAnswer in the constructor like-so:
class Pairs extends Screen {
constructor() {
super();
var pair1 = null;
var nPair1;
var solution;
var rightCounter = 0;
var licao, nS;
this.checkAnswer = this.checkAnswer.bind(this);
}
Or use and arrow function which gives you the exact reference to the this checkAnswer like-so:
checkAnswer = (pair, nPair) => {
//your code goes here ...
}
This way you will be able to call this.checkAnswer inside the scope of your pairScreen function or wherever you want to call the function like #Davelunny point out
Here is the page where I'm trying to display content. It's showing up blank. My application is a single page application, so most of the code is in the index.html file
verbPractice.html
<div>
<h1>Practice verbs here</h1>
<div class="row" ng-repeat="sentence in listOfSentences">
<div class="col-xs-12">
<p>{{sentence.first}} {{sentence.second}} {{sentence.third}}</p>
</div>
</div>
</div>
This page is linked to from another page called verbSelect.html. Here is the relevant code from that page
<div class="btn btn-primary" ui-sref="app.verbPractice" ng-click="storeInfo(); generateSentences()">Submit</div>
Both the above pages are under the same controller called verbController:
(function() {
'use strict';
angular.module('arabicApp')
.controller('verbController', ['$scope', 'verbFactory', 'pronounFactory', 'attachedFactory', function($scope, verbFactory, pronounFactory, attachedFactory){
//Gets verbs from server
$scope.verbArray = verbFactory.getVerbs().query(
function(response) {
$scope.verbArray = response;
}
);
//Gets pronouns from server
$scope.pronouns = pronounFactory.getPronouns().query(
function(response) {
$scope.pronouns = response;
}
);
$scope.attached = attachedFactory.getAttached().query(
function(response) {
$scope.attached = response;
}
);
//Stores the array of selected verbs
$scope.selectedVerbs = [];
$scope.numSelectedVerbs = 0;
//Searches theArray for name and returns its index. If not found, returns -1
$scope.searchArray = function(theArray, name) {
for (var i = 0; i < theArray.length; i++) {
if (theArray[i].name === name) {
return i;
}
}
return -1;
};
//Adds verbs to selected list
$scope.addToSelected = function(theVerb) {
var num = $scope.searchArray($scope.selectedVerbs, theVerb.name);
var divToChange = document.getElementById("verbSelect_"+theVerb.name);
if (num > -1) { //Found. Remeove it from selectedVerbs
$scope.selectedVerbs.splice(num, 1);
divToChange.className = divToChange.className.replace( /(?:^|\s)listItemActive(?!\S)/g , '' );
$scope.numSelectedVerbs = $scope.numSelectedVerbs - 1;
} else { //Not found. Add it in
$scope.selectedVerbs.push(theVerb);
divToChange.className += " listItemActive";
$scope.numSelectedVerbs = $scope.numSelectedVerbs + 1;
}
};
//Stores how many practice questions the user wants
$scope.howMany = 0;
//Stores what tense of verbs the user wants
$scope.verbTense = "Both";
//Stores what form the user wants
$scope.verbVoice = "Both";
//Include commands?
$scope.includeCommands = false;
//Sentense that will be generated
$scope.listOfSentences = [];
$scope.generateSentence = function(isCommand, theTense, theVoice) {
var sent = {"first": "", "second": "", "third": ""};
var attachedPicker = Math.floor(Math.random()*14);
var attachedToUse = $scope.attached[attachedPicker].attached;
var pronounPicker = Math.floor(Math.random()*14);
var pronounToUse = $scope.pronouns[pronounPicker].pronoun;
sent.first = pronounToUse;
var verbPicker = Math.floor(Math.random()*$scope.numSelectedVerbs);
var verbToUse = $scope.selectedVerbs[verbPicker][theTense][pronounToUse];
if (isCommand === true) {
sent.second = verbToUse;
} else {
if (theVoice === "Passive") {
if (theTense === "Past") { sent.second = "were"; }
else { sent.second = "are"; }
sent.third = verbToUse;
} else {
sent.second = verbToUse;
sent.third = attachedToUse;
}
}
return sent;
};
$scope.storeInfo = function() {
localStorage.setItem("howMany", $scope.howMany);
localStorage.setItem("verbTense", $scope.verbTense);
localStorage.setItem("verbVoice", $scope.verbVoice);
localStorage.setItem("includeCommands", $scope.includeCommands);
};
$scope.getStoredInfo = function() {
$scope.howMany = localStorage.getItem("howMany");
$scope.verbTense = localStorage.getItem("verbTense");
$scope.verbVoice = localStorage.getItem("verbVoice");
$scope.includeCommands = localStorage.getItem("includeCommands");
};
//Generates sentences using the variables from verbSelect
$scope.generateSentences = function() {
$scope.getStoredInfo();
var tensePicker;
var voicePicker;
var doCommand;
var rand;
for (var i = 0; i < $scope.howMany; i++) {
//Picks the verb tense
if ($scope.verbTense === "Both") {
rand = Math.floor(Math.random());
if (rand === 0) { tensePicker = "Past"; }
else { tensePicker = "Present"; }
} else {
tensePicker = $scope.verbTense;
}
//Picks the verb voice
if ($scope.verbVoice === "Both") {
rand = Math.floor(Math.random());
if (rand === 0) { voicePicker = "Active"; }
else { voicePicker = "Passive"; }
} else {
voicePicker = $scope.verbVoice;
}
//If the voice is passive, use past tense
if ($scope.verbVoice === "Passive") { tensePicker = "Past"; }
//Determines if the sentence will be a command sentence or not
if ($scope.includeCommands === true) {
rand = Math.floor(Math.random() * 6);
if (rand === 0) { doCommand = true; }
else { doCommand = false; }
} else {
doCommand = false;
}
var sentence = $scope.generateSentence(doCommand, tensePicker, voicePicker);
$scope.listOfSentences.push(sentence);
}
console.log($scope.listOfSentences);
};
}])
;
})();
The variables: howMany, verbTense, verbVoice, isCommand, are set on this verbSelect.html page using ng-model. Both the verbSelect.html page and verbPractice.html page are under the same controller.
Everything seems to be working fine. At the end of my generateSentences() function, I output $scope.listOfSentences to the log, and it shows up without any problems, the array is being populated just fine. However, in my verbPractice.html page, nothing is showing up except the <h1> heading. For some reason, even though the $scope.listOfSentences array is populated, ng-repeat doesn't seem to be looping. Does anyone have any idea why?
Sorry for the long post
Thanks for taking the time to read and answer this question!
Basically I've made a program where words are inputted and their definitions are found using Wordnik API. Each word is then displayed dynamically and the definition is shown on click. Here's that code:
function define(arr) {
return new Promise(function(resolve, reject) {
var client = [];
var definitions = {};
for (var i = 0, len = arr.length; i < len; i++) {
(function(i) {
client[i] = new XMLHttpRequest();
client[i].onreadystatechange = function() {
if (client[i].readyState === 4 && client[i].status === 200) {
if (client[i].responseText.length === 0) {
console.log(client[i].responseText);
client.responseText[0] = {
word: arr[i],
text: 'Definition not found'
};
}
definitions[arr[i]] = JSON.parse(client[i].responseText);
if (Object.keys(definitions).length === arr.length) {
resolve(definitions);
}
}
};
client[i].open('GET', 'http://api.wordnik.com:80/v4/word.json/' + arr[i] +
'/definitions?limit=1&includeRelated=false&sourceDictionaries=all&useCanonical=false&includeTags=false&api_key=',
true);
client[i].send();
})(i);
}
});
}
function makeFlashCards() {
var data = document.getElementById('inputText').value;
var wordsToDefine = ignore(makeArr(findUniq(data)));
define(wordsToDefine).then(function(result) {
success(result);
}).catch(function(reason) {
console.log('this shouldnt run');
});
}
function success(obj) {
document.getElementById('form').innerHTML = '';
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
addElement('div', obj[prop][0].word);
}
}
attachDefinition(obj);
}
function addElement(type, word) {
var newElement = document.createElement(type);
var content = document.createTextNode(word);
newElement.appendChild(content);
var referenceNode = document.getElementById('form');
document.body.insertBefore(newElement, referenceNode);
newElement.id = word;
newElement.className = "flashcards";
}
function attachDefinition(obj) {
var classArr = document.getElementsByClassName('flashcards');
for (let i = 0, len = classArr.length; i < len; i++) {
classArr[i].addEventListener('click', function() {
cardClicked.call(this, obj);
});
}
}
function cardClicked(obj) {
var el = document.getElementById(this.id);
if (obj[this.id].length !== 0) {
if (this.innerHTML.split(' ').length === 1) {
var img = document.createElement('img');
img.src = 'https://www.wordnik.com/img/wordnik_badge_a2.png';
el.innerHTML = obj[this.id][0].text
+ ' ' + obj[this.id][0].attributionText + '<br>';
el.style['font-weight'] = 'normal';
el.style['font-size'] = '16px';
el.style['text-align'] = 'left';
el.style['overflow'] = 'auto';
el.appendChild(img);
} else {
el.innerHTML = obj[this.id][0].word;
el.style['font-weight'] = 'bold';
el.style['font-size'] = '36px';
el.style['text-align'] = 'center';
el.style['overflow'] = 'visible';
}
}
}
When the define function is given an array with all valid words, the program works as expected however if any word in the array argument is not valid the program doesn't add click event handlers to each element. I think this might have to do with the catch being triggered.
When an invalid word is requested Wordnik API sends back an empty array which might be the root of this problem. I tried to account for this by adding
if (client[i].responseText.length === 0) {
console.log(client[i].responseText);
client.responseText[0] = {
word: arr[i],
text: 'Definition not found'
};
but this conditional never ends up running.
I need some way of filtering out the empty array responses so the catch is not triggered and the program can run smoothly.
When you get to if (client[i].responseText.length === 0) make sure that client[i].responseText is returning empty string. It is probably undefined in which case client[i].responseText.length will throw an error and this will cause the catch block to execute.
function makePromise() {
return new Promise(function(resolve, reject) {
var test = undefined;
if (test.length === 0) {
resolve("resolved");
}
});
}
makePromise().then(console.log).catch(function(res) {
console.log('Error was thrown')
});
Try changing that condition to:
if (client[i].responseText && client[i].responseText.length === 0)
I am trying to get the document of an Iframe after setting the iframe.src.
I am calling this in phantom-node.
The function returns an error when the iframe is empty:
fetchGuestbookEntries: function () {
var getGuestbookForPage = function (doc) {
var result = [];
var rows = doc.querySelectorAll('td[class="guestbook"]');
var date = "";
var entry = "";
for (var i = 0; i < rows.length; i++) {
date = i % 2 == 0 ? rows[i].innerText : date;
entry = i % 2 != 0 ? rows[i].innerText : entry;
if (date && entry) {
var info = date.split('\n').map(function (elem) {
return elem.replace('\n', '').trim();
});
result.push(
{
info: {
guestname: info[0],
date: new Date(info[3]).toISOString().slice(0, 10),
time: info[4].replace(/Uhr|h/gi, '').trim()
},
entry: entry.trim()
}
);
date = "";
entry = "";
}
}
return result;
};
var getPaginationSize = function () {
return document.querySelector('td[class="guestbook_navijump"]') ?
document.querySelector('td[class="guestbook_navijump"]').querySelectorAll('a').length : 0;
};
var getIframeDoc = function(ifrm) {
return ifrm.document ||
ifrm.contentDocument ||
ifrm.contentWindow.document;
};
var pagination = getPaginationSize();
var entries = [];
for (var i = 0; i <= pagination; i++) {
var paginationPageUrl = window.location.href + "?jump=" + i;
var iframe = document.createElement('iframe');
iframe.src = paginationPageUrl;
var doc = getIframeDoc(iframe);
entries.push(getGuestbookForPage(doc));
}
return entries;
}
Is there a way to get the document?
The error:
Uncaught TypeError: Cannot read property 'document' of null
at <anonymous>:2:21
at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)
I normally open the Page in PhantomJS.
You should be able to get it with this
document.getElementById('myframe').contentWindow.document