Whatsapp share button for web version - javascript

I have this script but its only share from mobile version.
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
var whatsapp_url = ".whatsapp://send?text=" + message;
window.location.href = whatsapp_url;
} else {
alert("Please use an Mobile Device to Share this Status");
}
});
});
Can anyone modify this?

This line
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
checks for mobile and if true, the share logic is executed. In the else branch (meaning it's not a mobile) you get an error message. If you want the same to happen in both versions, just omit the if:
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
//if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
var whatsapp_url = ".whatsapp://send?text=" + message;
window.location.href = whatsapp_url;
//} else {
//alert("Please use an Mobile Device to Share this Status");
}
});
});

According the WhatsApp docs: https://faq.whatsapp.com/general/chats/how-to-use-click-to-chat/?lang=en
To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext
Example: https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing`
The result should be something like:
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
// this 3 rows will be used for both - desktop and mobile
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var whatsapp_url = ".whatsapp://send?text=" + message;
} else {
var whatsapp_url = "https://wa.me/?text=" + message;
}
// again for both
window.location.href = whatsapp_url;
});
});

Related

JavaScript - Self-invoking function can't see functions from external script

I have a conceptual issue about scopes on the following code.
The code is a simple client-side validation script for two forms.
I used a self-invoking function to try a something different approach by avoiding to set all global variables but its behavior seems a bit weird to me.
I am still learning to code with JavaScript and I'm not an expert, but these advanced features are a bit complicated.
I don't want to use jQuery but only pure JavaScript in order to learn the basis.
<!-- Forms handling -->
<script src="validate_functions.js"></script>
<script>
(function main() {
var frmPrev = document.getElementById('frmPrev');
var frmCont = document.getElementById('frmCont');
var btnPrev = frmPrev['btnPrev'];
var btnCont = frmCont['btnCont'];
var caller = '';
var forename = '';
var surname = '';
var phone = '';
var email = '';
var privacy = '';
var message = '';
var infoBox = document.getElementById('info-box');
var infoBoxClose = infoBox.getElementsByTagName('div')['btnClose'];
btnPrev.onclick = function(e) {
submit(e);
};
btnCont.onclick = function(e) {
submit(e);
};
function submit(which) {
caller = which.target.name;
var errors = '';
if(caller == 'btnPrev') {
forename = frmPrev['name'].value.trim();
surname = frmPrev['surname'].value.trim();
phone = frmPrev['phone'].value.trim();
email = frmPrev['email'].value.trim();
message = frmPrev['message'].value.trim();
privacy = frmPrev['privacy'].checked;
}
if(caller == 'btnCont') {
phone = frmCont['phone'].value.trim();
email = frmCont['email'].value.trim();
message = frmCont['message'].value.trim();
}
errors = validateFields(caller, forename, surname, phone, email, privacy, message);
if(errors == '') {
var params = 'which=' + caller;
params += '&fname=' + forename;
params += '&sname=' + surname;
params += '&tel=' + phone;
params += '&email=' + email;
params += '&priv=' + privacy;
params += '&mess=' + message;
var request = asyncRequest();
request.open('POST', "send-mail.php", true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Content-length', params.length);
request.setRequestHeader('Connection', 'close');
request.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
if(this.responseText != null) {
infoBox.innerHTML = this.responseText;
} else {
infoBox.innerHTML = '<p>No data from server!</p>';
}
} else {
infoBox.innerHTML = '<p>Could not connect to server! (error: ' + this.statusText + ' )</p>';
}
}
}
request.send(params);
} else {
infoBox.innerHTML = errors;
}
infoBox.style.display = 'block';
}
infoBoxClose.onclick = function() {
infoBox.style.display = 'none';
infoBox.innerHTML = '';
};
function validateFields(_caller, _forename, _surname, _phone, _email, _privacy, _message) {
var errs = '';
if(_caller == 'btnPrev') {
errs += validateForename(_forename);
errs += validateSurname(_surname);
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
errs += validatePrivacy(_privacy);
}
if(_caller == "btnCont") {
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
}
return errs;
}
function asyncRequest() {
var request;
try {
request = new XMLHttpRequest();
}
catch(e1) {
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e2) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e3) {
request = null;
}
}
}
return request;
}
})();
Web console keeps telling me that single validate functions are not defined.
Why?
They should be loaded from the external script.. furthermore they should have a global scope.
Thank you in advance :)
Problem solved!
The path to the external script was incorrect.
Sorry for this rubbish! ^^"

Chrome Extension - Rerun extension script after redirecting current tab

I am trying to develop a chrome extension which parses data from the current tab and post it to a url which does processing on the data. In certain cases the page may need to be redirected so that certain get parameters are present. My popup.js can successfully do the redirect, but I need to click on the extension a second time to get it to run properly. Note: it runs properly if the page has the correct parameters. How can I adjust this so that the code reruns after the redirect and posts the new source to the specified url.
Here is my popup.js:
var url = "";
chrome.runtime.onMessage.addListener(function(request, sender) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
url = tabs[0].url;
if (url.search("[?&]view=list") == -1)
{
url = setGetParameter(url,'view','list');
chrome.tabs.update(tabs[0].id,{url:url});
process(request);
}
});
process(request);
});
function process(request) {
if (request.action == "getSource") {
message.innerText = request.source;
var data = new FormData();
data.append('source',request.source);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE) {
message.innerText = xhttp.responseText;
}
}
xhttp.open("POST","http://127.0.0.1:5000/api/scraper",true);
xhttp.send(data);
}
}
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
function setGetParameter(url, paramName, paramValue)
{
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
return url + hash;
}
window.onload = onWindowLoad;
Take a look at webRequest.onBeforeRedirect, this event fired when a redirect is about to be executed. You can listen to this event and do your logic again.
Don't forget to declare webRequest permission along with host permissions for any hosts whose network requests you want to access in you manifest.json.

De-/activate getfeature-request via button

I have an Openlayers3-map with more than one WMS-Layer. I want to add a button (for every queryable layer) so the user can decide to query the wms-layer or not.
var getfeature = function(click) {
map.on(click, function (evt) {
document.getElementById('info').innerHTML = '';
var viewResolution = (view.getResolution());
var url = wms_url.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, projection,
{
'INFO_FORMAT': 'text/html'
});
if (url) {
document.getElementById('info').innerHTML =
'<iframe seamless src="' + url + '"></iframe>';
}
});
}
This part works fine so far.
Now combine the getfeature-request with the "user-interface" (here just a checkbox)
var userquery = function() {
var $input = $( this );
//checkbox true/false
if($input.prop("checked")) {
//change cursor appearance
map.getViewport().style.cursor = 'help';
//getfeature-request on singleclick
getfeature('singleclick');
}
else {
//change cursor appearance, when checkbox is unchecked
map.getViewport().style.cursor = '';
//WHAT TO DO HERE???
//...
}
};
the checkbox with id="cursor10"
var checkbox = document.getElementById('cursor10');
and add the functionality via
checkbox.onchange = userquery;
At the moment the getfeature-function is continue working once it's activated.
What do I need to do, so the getfeature function will stop working when the checkbox is unchecked? Or any ideas for another approach?
You can use the unByKey() function to unregister the event listener of the map by its key
see: http://jsfiddle.net/d1wrkb95/2/
var mapEventKey;
var getfeature = function(click) {
mapEventKey = map.on(click, function (evt) {
document.getElementById('info').innerHTML = '';
var viewResolution = (view.getResolution());
var url = wms_url.getGetFeatureInfoUrl(
evt.coordinate, viewResolution, projection_to,
{
'INFO_FORMAT': 'text/html'
});
if (url) {
document.getElementById('info').innerHTML =
'<iframe seamless src="' + url + '"></iframe>';
}
});
};
var userquery = function() {
var $input = $( this );
//checkbox true/false
if($input.prop("checked")) {
//cursor ändern
map.getViewport().style.cursor = 'help';
//getfeatureabfrage bei einzelklick
getfeature('singleclick');
}
else {
map.unByKey(mapEventKey);
map.getViewport().style.cursor = '';
}
};

Firefox plugin for SSL

I am trying to make a plugin for Mozilla which prints simple SSL details like Name and certificate is valid till what date.
Here is my CODE :
var data = require("sdk/self").data;
var text_entry = require("sdk/panel").Panel({
width: 412,
height: 400,
contentURL: data.url("text-entry.html"),
contentScriptFile: data.url("get-text.js")
});
require("sdk/widget").Widget({
label: "Text entry",
id: "text-entry",
contentURL: "http://www.mozilla.org/favicon.ico",
panel: text_entry,
});
text_entry.on("show", function() {
text_entry.port.emit("show");
});
text_entry.port.on("text-entered", function (text) {
console.log(text);
var requrl = require("sdk/tabs").activeTab.url;
console.log(requrl);
const {Ci,Cc} = require("chrome");
//var req = new XMLHttpRequest();
var req = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
req.open('GET', requrl, false);
req.onload = function(e) {
console.log(req);
let channel = req.channel;
console.log(requrl);
if (! channel instanceof Ci.nsIChannel) {
console.log("No channel available\n");
return;
}
console.log(requrl);
var secInfo = req.securityInfo;
var cert = secInfo.QueryInterface(Ci.nsISSLStatusProvider).SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert ;
var validity = cert.validity.QueryInterface(Ci.nsIX509CertValidity);
console.log(requrl);
console.log("\tCommon name (CN) = " + cert.commonName + "\n");
console.log("\tOrganisation = " + cert.organization + "\n");
console.log("\tIssuer = " + cert.issuerOrganization + "\n");
console.log("\tSHA1 fingerprint = " + cert.sha1Fingerprint + "\n");
console.log("\tValid from " + validity.notBeforeGMT + "\n");
console.log("\tValid until " + validity.notAfterGMT + "\n");
};
});
It says, XMLHttpRequest is not defined. Also the channel structure is empty when printed to console.
Not exactly sure where your code is broken or why (as I'm to lazy to replicate the missing pieces like the text-entry.html).
Anyway, here is a fast test that works for me in both, and SDK add-on and Scratchpad:
// Save as your main.js.
// Alternatively execute in a Scratchpad in about:newTab.
var sdk = false;
if (!("Cc" in this)) {
try {
// add-on SDK version
this.Cc = require("chrome").Cc;
this.Ci = require("chrome").Ci;
this.log = console.error.bind(console);
this.sdk = true;
log("using SDK");
}
catch (ex) {
// Scratchpad on about:newtab version
this.Cc = Components["classes"];
this.log = console.log.bind(console);
log("using scratchpad");
}
}
let r = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
r.open("GET", "https://tn123.org/");
r.onloadend = function(e) {
let ok = "OK";
try {
log(e);
// Note: instanceof is an implicit QueryInterface!
log(this.channel instanceof Ci.nsIChannel);
log(this.channel.securityInfo instanceof Ci.nsISSLStatusProvider);
let status, cert;
log(status = this.channel.securityInfo.SSLStatus);
log(status.cipherName);
log(cert = status.serverCert);
log("Common name (CN) = " + cert.commonName);
log("Organisation = " + cert.organization);
log("Issuer = " + cert.issuerOrganization);
log("SHA1 fingerprint = " + cert.sha1Fingerprint);
log("Valid from " + cert.validity.notBeforeGMT);
log("Valid until " + cert.validity.notAfterGMT);
for (let k of Object.keys(cert)) {
if (k[0].toUpperCase() === k[0]) {
// skip constants
continue;
}
let v = cert[k];
if (typeof v === "function") {
continue;
}
log(k + ": " + v);
}
}
catch (ex) {
log("Caught exception", ex);
ok = ex;
}
if (sdk) {
require("notifications").notify({
title: "Test done",
text: "HTTPS test done; result=" + ok
});
}
log("HTTPS test done; result=" + ok);
};
r.send();
PS: I'm using console.error in the SDK, because:
If you're developing your add-on using the Extension Auto-installer,
then the add-on is installed in Firefox, meaning that messages will
appear in the Browser Console. But see the discussion of logging
levels: by default, messages logged using log(), info(), trace(), or
warn() won't be logged in these situations.
Have you written this in the content script? If so, you can't make requests from the content script (which is why it says it does not exist). You need to write this in main.js. If you want to communicate with your content script (html, window, etc) you'll have to use message passing: port.emit and addon.emit to send messages and port.on and addon.on to listen for messages.

JavaScript: "Syntax error missing } after function body"

Ok, so you know the error, but why on earth am I getting it?
I get no errors at all when this is run locally, but when I uploaded my project I got this annoying syntax error. I've checked the Firebug error console, which doesn't help, because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}
}
function Login() {
// Grab username and password for login
var uName = document.getElementById('uNameBox').value;
var pWord = document.getElementById('pWordBox').value;
ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}
function Chat() {
// Get username from recipient box
var user = document.getElementById('recipient').value;
self.location = 'index.php?to=' + user;
}
function SendMessage() {
// Grab message from text box
var from = readCookie('privateChat');
var to = getUrlVars()['to'];
var msg = document.getElementById('msgBox').value;
ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
// Reset the input box
document.getElementById('msgBox').value = "";
}
function GetMessages() {
// Grab account hash from auth cookie
var aHash = readCookie('privateChat');
var to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
var textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The problem is your script on your server is in one line, and you have comments in it. The code after // will be considered as comment. That's the reason.
function ToServer(cmd, data) { var xmlObj = new XMLHttpRequest(); xmlObj.open('POST', 'handler.php', true); xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlObj.send(cmd + data); xmlObj.onreadystatechange = function() { if(xmlObj.readyState === 4 && xmlObj.status === 200) { if(cmd == 'cmd=push') { document.getElementById('pushResponse').innerHTML = xmlObj.responseText; } if(cmd == 'cmd=pop') { document.getElementById('messages').innerHTML += xmlObj.responseText; } if(cmd == 'cmd=login') { if(xmlObj.responseText == 'OK') { self.location = 'index.php'; } else { document.getElementById('response').innerHTML = xmlObj.responseText; } } } };}function Login() { // Grab username and password for login var uName = document.getElementById('uNameBox').value; var pWord = document.getElementById('pWordBox').value; ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() { if(getUrlVars()['to'] != null) { setInterval(GetMessages(), 1000); }}function Chat() { // Get username from recipient box var user = document.getElementById('recipient').value; self.location = 'index.php?to=' + user;}function SendMessage() { // Grab message from text box var from = readCookie('privateChat'); var to = getUrlVars()['to']; var msg = document.getElementById('msgBox').value; ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box document.getElementById('msgBox').value = "";}function GetMessages() { // Grab account hash from auth cookie var aHash = readCookie('privateChat'); var to = getUrlVars()['to']; ToServer('cmd=pop','&account=' + aHash + '&to=' + to); var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null;}function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;}
You're missing a semi-colon:
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}; //<-- Love the semi
}
Additional missing semi-colon:
// Start checking of messages every second
window.onload = function() {
if (getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; //<-- Love this semi too!
I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming. If not, remove the first portion and see. This is a technique which I follow when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.
This will help us to identify the actual point of error.
I do not see any problem with this script.
This may not be the exact solution you want, but it is a way to locate and fix your problem.
It looks like it's being interpreted as being all on one line. See the same results in Fiddler 2.
This problem could do due to your JavaScript code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:
// Reset the input box
...to...
/* Reset the input box */
Adding a note: very strangely this error was there very randomly, with everything working fine.
Syntax error missing } after function body | At line 0 of index.html
It appears that I use /**/ and //🜛 with some fancy Unicode character in different parts of my scripts for different comments.
This is useful to me, for clarity and for parsing.
But if this Unicode character and probably some others are used on a JavaScript file in comments before any JavaScript execution, the error was spawning randomly.
This might be linked to the fact that JavaScript files aren't UTF-8 before being called and read by the parent page. It is UTF-8 when the DOM is ready. I can't tell.
It seems there should be added another semicolon in the following code too:
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; <---- Semicolon added
Also here in this code, define the var top of the function
function readCookie(name) {
var i;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
"Hm I think I found a clue... I'm using Notepad++ and have until recently used my cPanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "
I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.

Categories