/
telefonilo.js
86 lines (75 loc) · 2.57 KB
/
telefonilo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
(function (global) {
// Helper functions
/**
* Check if the client is on a mobile device
* @returns {Boolean}
*/
function isMobile() {
var testExp = new RegExp('Android|webOS|iPhone|iPad|' +
'BlackBerry|Windows Phone|' +
'Opera Mini|IEMobile|Mobile', 'i');
return testExp.test(navigator.userAgent);
}
/**
* Verify if the given function is a valid encryption function,
* @param {function} _function
* @returns {Boolean}
*/
function isValidEncryptionFunction(_function) {
var mockData = '+213123456789';
return (
typeof _function === 'function' &&
typeof _function(mockData) === 'string' &&
_function(mockData) !== mockData
);
}
// Call the constructor without `new`
var Telefonilo = function (querySelector, isEncrypted, encrypTionFunction) {
return new Telefonilo.init(querySelector, isEncrypted, encrypTionFunction);
}
// Not implemented, for the moment
// Telefonilo.prototype = {
// validatePhone: function(){
// return -1;
// }
// };
Telefonilo.init = function (querySelector, isEncrypted, encrypTionFunction) {
var self = this;
self.querySelector = querySelector || '.phone-num';
self.isCrypted = isEncrypted && encrypTionFunction;
if (self.isCrypted && !isValidEncryptionFunction(encrypTionFunction))
throw new Error('This encryption function is not valid!');
if (isMobile()) {
var phoneNumberTags = document.querySelectorAll(self.querySelector);
for (var i = 0; i < phoneNumberTags.length; i++) {
var el = phoneNumberTags[i];
var aTag = document.createElement('a');
aTag.href = 'tel://' + (self.isCrypted ? encrypTionFunction(el.innerText) : el.innerText);
aTag.innerText = el.innerText;
el.innerHTML = '';
el.appendChild(aTag);
}
} else {
if (self.isCrypted) {
var phoneNumberTags = document.querySelectorAll(self.querySelector);
for (var i = 0; i < phoneNumberTags.length; i++) {
phoneNumberTags[i].innerText = encrypTionFunction(phoneNumberTags[i].innerText);
}
}
}
};
Telefonilo.init.prototype = Telefonilo.prototype;
// Check if it is CommonJS a environments (example: Node)
if (typeof module === 'object' && module.exports) {
module.exports = Telefonilo;
} else {
// Export as browser globals (global is window)
global.Telefonilo = Telefonilo;
}
/* start-test-block */
Telefonilo._api = {
isValidEncryptionFunction: isValidEncryptionFunction,
isMobile: isMobile,
}
/* end-test-block */
})(this);