Immediate play sound on button click in HTML page - buttonclick

In my HTML page I have 9 images for dialing numbers and one text box that shows the pressed numbers. I want each of those images to immediately play beep sound when users click on them. I tried to use embed with hidden property and navigate it's source to .wav sound.
It is working OK, but when I press the images one after another immediately, it cannot play sound and just bees once at the end.
Is there any faster way of playing a .wav sound on 'onclick' method?

If you only need to support recent browsers, then HTML 5 offers you the Audio object
to load/buffer your sound:
var snd = new Audio("file.wav");
to play the sound:
snd.play();
to re-cue it to the beginning (so that you can play it again):
snd.currentTime=0;

This answer https://stackoverflow.com/a/7620930/1459653 by #klaustopher (https://stackoverflow.com/users/767272/klaustopher) helped me. He wrote:
HTML5 has the new <audio>-Tag that can be used to play sound. It
even has a pretty simple JavaScript Interface:
<audio id="sound1" src="yoursound.mp3" preload="auto"></audio>
<button onclick="document.getElementById('sound1').play();">Play
it</button>
Here's how I implemented his advice so that clicking on the Font Awesome icon "fa-volume-up" (located on the Web page after "mule.") results in "donkey2.mp3" sound playing (note: mp3 doesn't play in all browsers).
<p>In short, you're treated like a whole person, instead of a rented mule. <audio id="sound1" src="assets/donkey2.mp3" preload="auto"></audio><a class="icon fa-volume-up" onclick="document.getElementById('sound1').play();"></a>

You can use embed element for play sounds, but you've to check the formats supported by the different browsers.
Embed element on MDN
<a onclick="playSound('1.mp3')">
<img src="1.gif">
</a>
<div id="sound"></div>
<script>
var playSound = function (soundFile) {
$("#sound").html("<embed src=\"" + soundFile + "\" hidden=\"true\" autostart=\"true\" />");
}
</script>

This code lets you put in a picture button; when click you get a sound. It works with Google Chrome and Microsoft Edge but I can't get it to work in Internet Explorer. I'm using html 5 codes; please copy and paste and add you own samples.
</head>
<body>
<script>
var audio = new Audio("/Sample.wav ");
audio.oncanplaythrough = function ( ) { }
audio.onended = function ( ) { }
</script> <input type="image" src="file://C:/Sample.jpg" onclick="audio.play ( )">
</body>
</html>
more on codes look at
http://html5doctor.com/html5-audio-the-state-of-play/

Example based on accepted answer (Tested in Chrome 70), but I didn't need to re-cue:
<button onclick="snd.play()"> Click Me </button>
<script>
var snd = new Audio("/Content/mysound.wav");
</script>

This is what I would do to play sound effects:
<html>
<body>
<audio id="sfx"><source src="mysound.mp3"></audio>
<button onclick="playsound()" id="button">Play a sound!</button>
<script> function playsound() {
var sfx = document.getElementById("sfx");
sfx.autoplay = 'true';
sfx.load();}
Or you can run this snippet:
function playsound() {
var mysound = document.getElementById("mysound");
mysound.autoplay = 'true';
mysound.load();
}
button {
color: blue;
border-radius: 24px;
border: 5px solid red;
}
body {
background-color: #bfbfbf;
}
<html>
<body>
<audio id='mysound'><source src="click.mp3"><!-- "click.mp3" isn't a sound effect uploaded to the snippet, because I don't think you can upload sfx to snippets. (I'm new to stackoverflow, so there might be a way) But if you actually use a sound effect in that folder that you're using, it works. --></audio>
<button id='btn' onclick='playsound()'>Play a sound!</button>
</body>
</html>

Related

Is there a way to play background music using Google Apps Script?

I am creating an add-on which would ask the user to select music from a list and it would play it as background music. But previous posts show a sidebar with the user manually pressing the play button. I am wondering if there is a way to play it with Google Apps Script only. Also what would be helpful is if there was a volume property to set the volume?
My Code:
function onOpen(){
DocumentApp.getUi()
.createMenu("Background Music Add-On")
.addItem("Select Music","music")
.addItem("Set Volume","musicVol")
.addToUi();
}
//music selection
function music(){
var musicName = DocumentApp.getUi()
.prompt("Please select one of the music names:\n\nElevator Music,\nLeaf Rag.\nso on...")
switch(musicName){
case "Elevator":
//code to play music Elevator
break;
//So On
}
}
Playing music from a Playlist stored on your Google Drive
This script allows you to store mp3's on your Google Drive. It allows you to select which files you wish to listen too via a playlist. You must start the playlist the first time manually but then the rest of the selections play automatically. The script converts the mp3 files into dataURI's and loads them into the audio element. You can skip over the current selection and you can restart the playlist when it completes.
Code.gs
function onOpen() {
SpreadsheetApp.getUi().createMenu('My Music')
.addItem('Launch Music', 'launchMusicDialog')
.addItem('Create New Music List', 'createMusicList')
.addToUi();
}
function convMediaToDataUri(filename){
var filename=filename || "default.mp3";
var folder=DriveApp.getFolderById("Music Folder Id");
var files=folder.getFilesByName(filename);
var n=0;
while(files.hasNext()) {
var file=files.next();
n++;
}
if(n==1) {
var blob=file.getBlob();
var b64DataUri='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
Logger.log(b64DataUri)
var fObj={filename:file.getName(),uri:b64DataUri}
return fObj;
}
throw("Multiple Files with same name.");
return null;
}
function launchMusicDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('music1');
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Music');
}
function createMusicList() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("MusicList");
var folder=DriveApp.getFolderById("Music Folder Id");
var files=folder.getFiles();
var mA=[['Item','File Name','File Type','File Id','Play List']];
sh.clearContents()
var n=1;
while(files.hasNext()) {
var file=files.next();
mA.push([n++,file.getName(),file.getMimeType(),file.getId(),'']);
}
sh.getRange(1,1,mA.length,mA[0].length).setValues(mA);
sh.getRange(2,2,sh.getLastRow()-1,sh.getLastColumn()-1).sort({column:2,ascending:true});
sh.getRange(2,5,sh.getLastRow()-1,1).insertCheckboxes();
}
function getPlaylist() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('MusicList');
var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
var vA=rg.getValues();
var pl=[];
for(var i=0;i<vA.length;i++) {
if(vA[i][4]) {
pl.push(vA[i][1]);
}
}
return pl;
}
music1.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
label{margin:2px 10px;}
</style>
</head>
<script>
var selectionList=[];
var gVolume=0.2;
var index=0;
$(function(){
document.getElementById('msg').innerHTML="Loading Playlist";
google.script.run
.withSuccessHandler(function(pl){
selectionList=pl;
console.log(pl);
google.script.run
.withSuccessHandler(function(fObj){
$('#audio1').attr('src',fObj.uri);
var audio=document.getElementById("audio1");
audio.volume=gVolume;
audio.onended=function() {
document.getElementById('status').innerHTML='Ended...';
playnext();
}
var msg=document.getElementById('msg');
msg.innerHTML="Click play to begin playlist. Additional selections will begin automatically";
audio.onplay=function() {
document.getElementById('msg').innerHTML='Playing: ' + selectionList[index-1];
document.getElementById('status').innerHTML='Playing...';
document.getElementById('skipbtn').disabled=false;
}
audio.onvolumechange=function(){
gVolume=audio.volume;
}
})
.convMediaToDataUri(selectionList[index++]);
})
.getPlaylist();
});
function playnext() {
if(index<selectionList.length) {
document.getElementById('status').innerHTML='Loading...';
document.getElementById('msg').innerHTML='Next Selection: ' + selectionList[index];
google.script.run
.withSuccessHandler(function(fObj){
$('#audio1').attr('src',fObj.uri);
var audio=document.getElementById('audio1');
audio.volume=gVolume;
audio.play();
})
.convMediaToDataUri(selectionList[index++]);
}else{
document.getElementById('status').innerHTML='Playlist Complete';
document.getElementById('msg').innerHTML='';
document.getElementById('cntrls').innerHTML='<input type="button" value="Replay Playlist" onClick="replayPlaylist()" />';
}
}
function replayPlaylist() {
index=0;
document.getElementById('cntrls').innerHTML='';
playnext();
}
function skip() {
var audio=document.getElementById('audio1');
document.getElementById('skipbtn').disabled=true;
audio.pause();
index++;
playnext();
}
</script>
<body>
<div id="msg"></div>
<audio controls id="audio1" src=""></audio><br />
<div id="status"></div>
<div><input type="button" id="skipbtn" value="Skip" onClick="skip()" disabled /></div>
<div id="cntrls"></div>
</body>
</html>
Please read through the code. You need to add a music folder id and a couple of default.mp3's. The createMusicList() function reads your Music Folder and Loads them into a sheet named 'MusicList' with columns of "Item", "File Name", "File Type" ,"File Id", and PlayList. The last column is just a column of unchecked checkboxes for you to make your current playlist selection. Only one playlist for now, so you can enjoy building your own.
Here's what the dialog looks like:
And here's an image of my MusicList Sheet:
This is where you make your playlist selections.
Audio Properties and Methods
Apps Script Documentation
Latest Script Code
I used the answer to this question as a starting point: playing sound with google script
You would need to open a html sidebar and use an audio tag, to do this you can use the HtmlService class [1].
As a total background you can't, the sidebar must be always open to play the music. But you could still play the audio while editing the document.
To add the audio setting you can add the controls attribute to the audio tag [2]. For playing the audio automatically you can add the autoplay attibute [3].
Here is the code I implemented to achieve your goal. The code gets the selected value and uses it to change the autoplay value to true and to display the audio as well. Also, when the select element is on focus, it gets the previous selected value so later (when a new value is selected) it can be used to stop the previous audio selection and not display it anymore. For these purposes I used the onchange [4] and the onfocus [5] events.
Code.gs
var SIDEBAR_TITLE = 'Sidebar Musicbox';
function onOpen(e) {
DocumentApp.getUi()
.createMenu('Custom Menu')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle(SIDEBAR_TITLE);
DocumentApp.getUi().showSidebar(ui);
}
Sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div class="sidebar branding-below">
<p>
A little music for your enjoyment!
</p>
<form>
<select id="music" onchange="playSelection();" onfocus="setOldValue(this.value);">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<br>
<audio id="player0" controls style="display:none">
<source src="[WEB-URL-FOR-MP3-FILE]" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<audio id="player1" controls style="display:none">
<source src="[WEB-URL-FOR-MP3-FILE]" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<audio id="player2" controls style="display:none">
<source src="[WEB-URL-FOR-MP3-FILE]" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<br>
<div id="sidebar-status"></div>
</div>
<div class="sidebar bottom">
<span class="gray branding-text">Docs Add-on Sound Demo</span>
</div>
</body>
<script>
var previousValue;
//Function called when select onFocus
function setOldValue(e) {
previousValue = e;
}
//Function called when selected value change
function playSelection() {
//Get the value for the selected option
var selectedValue = document.getElementById("music").value;
//Latest and previous selection IDs
var player = "player" + selectedValue;
var previousPlayer = "player" + previousValue;
//Stop and don't display the previous selection of audio
document.getElementById(previousPlayer).style.display = "none";
document.getElementById(previousPlayer).autoplay = false;
document.getElementById(previousPlayer).load();
//Play and display the new selection and put the focus on it
document.getElementById(player).style.display = "block";
document.getElementById(player).autoplay = true;
document.getElementById(player).load();
document.getElementById(player).focus();
}
</script>
</html>
[1] https://developers.google.com/apps-script/guides/html/
[2] https://www.w3schools.com/tags/att_audio_controls.asp
[3] https://www.w3schools.com/tags/att_audio_autoplay.asp
[4] https://www.w3schools.com/jsref/event_onchange.asp
[5] https://www.w3schools.com/jsref/event_onfocus.asp

Restart a GIF animation when you click on a text link

I have some GIF animations that I want to display in a webpage. Imagine a picture gallery made of GIFs that plays only once then they froze :)
I would like to restart their animation every time I click on a text link. I updated a jsfiddle I found here, that does what I want, but when I click on the GIF, not on a text link.
Let's say I have 4 GIFs, I would like something like:
restart1 text link - GIF1 image
restart2 text link - GIF2 image
restart3 text link - GIF3 image
restart4 text link - GIF4 image
http://jsfiddle.net/GS427/97/
Thank you!
The thing your script does that restarts the GIF animation is to change the src attribute which reloads the gif.
You can do this in many different ways, here is an example:
http://jsfiddle.net/GS427/100/
<a onclick='$("#img").attr("src","https://dl.dropboxusercontent.com/u/908148/once.gif");' href="#">this</a>
You could extract it into a JavaScript function that take the image url as parameter. For example
function changeImage(imageUrl){
$('#img').attr('src',imageUrl);
}
And then use this for example:
<button onclick="changeImage('http://image1-url')">Image 1</button>
<button onclick="changeImage('http://image2-url')">Image 2</button>
<button onclick="changeImage('http://image3-url')">Image 3</button>
<button onclick="changeImage('http://image4-url')">Image 4</button>
You need to assign an id to your link (a), let's use the id aniclk for this example.
Replace
this
with this:
<a id="aniclk" href="#">this</a>
Notice the id="aniclk".
You'll want to change your Javascript to this:
$(function(){
var image = new Image();
image.src ='https://dl.dropboxusercontent.com/u/908148/once.gif';
$('#aniclk').click(function(){
$('#img').attr('src',image.src);
});
});
Working example:
$(function() {
var image = new Image();
image.src = 'https://dl.dropboxusercontent.com/u/908148/once.gif';
$('#aniclk').click(function() {
$('#img').attr('src', image.src);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is an animated GIF that plays once.</p>
<p>If you click on it, replay animation</p>
<img id="img" height="100px" width="100px" src="https://dl.dropboxusercontent.com/u/908148/once.gif" border="1">
<p>I want to restart the animation when click on <a id="aniclk" href="#">this</a> not the image</p>
Be aware that you will need JQuery for this.

Changing html content onclick chrome extension

Hello and thanks for reading my question. I'll warn you, it will probably seem dull to most of you, but I just can't get it working.
It's about a chrome extension I'm trying to write for my audio stream. Here's what I'm trying to do:
A small icon, that when is clicked once starts playing music, and when is clicked again stops, and so on...
Here's what I've tried:
<!doctype html>
<html>
<head>
</head>
<body>
<script src="popup.js"></script>
<div id="music"></div>
</body>
</html>
and popup.js
var well=0
//Executed when the extension's icon is clicked
chrome.browserAction.onClicked.addListener(function(tab)
{
if(well>0)
{
var well=0;
document.getElementById('music').innerHTML= '<iframe src="#" width="100" height="100"></iframe>';
}
else
{
var well=1;
document.getElementById('music').innerHTML= '<iframe src="http://electro.piratefm.ro/popup.html" width="100" height="100"></iframe>';
}
});
What's happening is that when the extension is loaded, no music plays. When you click it, it starts playing and everything's fine. When you click it again, it stops for a couple of seconds then starts playing again. I need it to stop until you click it again.
Thanks for reading and sorry if it's already been asked or if it's dull.
I fixed it, my js skills are horrible so it was a dumb mistake, this is the fixed version:
var well=0
//Executed when the extension's icon is clicked
chrome.browserAction.onClicked.addListener(function(tab)
{
if(well==1)
{
well=0;
document.getElementById('music').innerHTML= '<iframe src="#" width="100" height="100"></iframe>';
}
else
{
well=1;
document.getElementById('music').innerHTML= '<iframe src="http://electro.piratefm.ro/popup.html" width="100" height="100"></iframe>';
}
});

How to disable link to phone number when on Desktop?

How can I add a phone number to a website that is clickable but hides the link when I'm browsing on a website that doesn't support touch.
I could use Modernizr to set it up although. I don't know how.
<p><img src="assets/images/bt_calltoaction.gif" alt="View Projects" width="306" height="60"></p>
Could you just have the code in twice? i.e...
<div class="desktoptel">0800 000 000</div>
<div class="mobiletel"><a href="tel:0800-000-000">0800-000-000</div>
Then just 'display:none;' on the relevant class depending on your browser sizes?
I was just dealing with this issue, looking up solutions, and I found this thread (and a few others). I have to confess that I couldn't get any of them to work properly. I'm sure I was doing something wrong, BUT I did figure out a cheat.
As others have pointed out, changing the CSS to hide the visible link indication (color, text-decoration, cursor) is the first and easiest step. The cheat is to define a title for the tel link.
<p>Just call us at <a class="cssclassname" href="tel:18005555555"
title="CLICK TO DIAL - Mobile Only">(800) 555-5555</a>.</p>
By doing this, not only is the visible indicator of a link disguised (via CSS - see examples from others), but if someone does hover over the link, the title will pop up and say "CLICK TO DIAL - Mobile Only". That way, not only is there a better user experience, but your client doesn't accuse you of having a broken link!
For me the easiest, yet simplest method without any new classes / setup is via css:
a{
color: #3399ff;
}
a[href^="tel"]:link,
a[href^="tel"]:visited,
a[href^="tel"]:hover {
text-decoration: none;
color: #000;
pointer-events: none;
cursor: default;
}
/* Adjust px here (1024px for tablets maybe) */
#media only screen and (max-device-width: 480px) {
a[href^="tel"]:link,
a[href^="tel"]:visited,
a[href^="tel"]:hover {
text-decoration: underline;
color: #3399ff;
pointer-events: auto;
cursor: pointer;
}
}
Html just goes like this:
(+12)3 456 7
This works for modern browsers & IE 11+. If you need to include 8 < IE < 11 add the following to your javascript, since pointer-events dont work in IE:
var msie = window.navigator.userAgent.indexOf("MSIE ");
if (msie > 0){
var Elems = [], Tags = document.querySelectorAll("a[href^='tel']");
//Nodelist to array, so we're able to manipulate the elements
for (var i = 0; i < Tags.length; i++ ) {
Elems[ i ] = Tags[ i ];
}
for(var i = 0; i < Elems.length; i++){
Elems[ i ].removeAttribute('href');
}
}
EDIT: i found another answer on another thread, that may be useful for you - SO - Answer
I recently had this same problem. This problem is all over stackoverflow and everywhere else. How do you hide 'tel:' prefix and keep it from blowing up in regular browsers. There's no good single answer.
I ended up doing it this way:
first I use metalanguage to filter browser vs mobile (like php/coldfusion/perl) based on useragent string:
regular exp match for "/Android|webOS|iPhone|iPad|BlackBerry/i",CGI.HTTP_USER_AGENT
that gives me an if/else condition for desktop browser vs phone.
Next, my href tag looks like this: <a class="tel" id='tel:8005551212' href=''>800-555-1212</a>
Use CSS to style the .tel class in desktop stylesheet so it doesn't look like a link to desktop browsers. the phone number can still be clicked but its not obvious, and it wont do anything:
/* this is in default stylesheet, styles.css: */
.tel{
text-decoration:none;
color: #000;
cursor:default;
}
/* it should be re-styled in mobile css: */
.tel{
text-decoration: underline;
color: #0000CC;
cursor:auto;
}
Finally, I do a little jquery on the mobile links. The jQuery gets the id from the a.tel class, and inserts it into the href property, which makes it clickable for phone users.
The whole thing looks like this:
<!-- get regular CSS -->
<link rel="stylesheet" href="styles/styles.css" type="text/css" media="Screen" />
<!-- get user agent in meta language. and do if/else on result.
i'm not going to write that part here, other than pseudocode: -->
if( device is mobile ) {
<!-- load mobile CSS -->
<link rel="stylesheet" href="styles/mobile.css" type="text/css" media="handheld" />
<!-- run jQuery manipulation -->
<script>
$(function(){$('a.tel').prop('href',$('a.tel').prop('id'));});
</script>
}
<p> Call us today at <a class="tel" id='tel:8005551212' href=''>800-555-1212</a>!</p>
One caveat to this approach: id's should be unique. If you have duplicate phone numbers on a page that you want to link, change the id to name, then you use jQuery to loop through them.
You could use css media queries to control when its viewed as link and when not.
#media(min-width:768px){
a[href^="tel:"] {
pointer-events: none;
}
}
anything below 768px will work as link, above that, just as text.
if you just wanted to disable the click on the mobile screens:
if(typeof window.orientation !== 'undefined'){
$('a[href^="tel:"]').on('click', function(e){
e.preventDefaults();
});
}
Hope this helps :)
I've had success with this using Modernizr, specifically the touch test. It's not a perfect solution in that it doesn't do anything to help tablets or touch-enabled laptops, but it works in most desktop browsing situations.
HTML:
Call us at: 1-800-BOLOGNA
CSS:
.no-touch a.call-us {
color: black; /* use default text color */
pointer-events: none; /* prevents click event */
cursor: text; /* use text highlight cursor*/
}
The above CSS targets links with class="call-us" on non-touch devices which covers the majority of desktops.
Note that pointer-events is supported in all modern browsers but IE only supports it in versions 11+. See the compatibility chart.
Another solution, still imperfect, would be to use Modernizr.mq along with Modernizr.touch to detect screen width and touch capability and then inject the phone link with jQuery. This solution keeps the phone link out of the source code and then only appears on touch devices smaller than a certain width (say 720px which will probably cover most phones but exclude most tablets).
Ultimately, it's up to the browser vendors to come up with a bulletproof solution here.
I found the best way. I get that this is old, but I found a very easy way of doing this.
Using this code below
888-555-5555
//This is the logic you will add to the media query
.not-active {
pointer-events: none;
cursor: default;
}
In your CSS make use of media queries.
So make a media query for all desktops
#media only screen and (min-width: 64em) {
/* add the code */
.not-active {
pointer-events: none;
cursor: default;
}
}
Now all desktop sized pages wont be able to click on it.
it seems this could be done with a simple media query for most browsers. Something like this is working like a charm for me:
<style type="text/css">
#mobil-tel {
display:none;
}
#media (max-width: 700px) {
#mobil-tel {
display:block;
}
#desktop-tel{
display:none;
}
}
</style>
and on the desktop link, leave out the 'href', on the mobile link, put in the 'href'.
Just thought I would add my two-cents worth to (what is turning out to be a rather lengthy) discussion.
I basically use the onClick event (on the link) to execute Javascript to return a boolean true or false. If the return value is true, i.e. some variable or function that tests if the device is a phone returns a value true, then the href URL is followed by the browser. If the the return value is false, then the href URL becomes, in effect, inactive. (Standard HTML behavior, way before HTML5.)
Here is what I mean:-
<html>
<head>
<title>tel markup example</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> <!-- Does not really matter what version of jQuery you use -->
<script>
var probablyPhone = ((/iphone|android|ie|blackberry|fennec/).test(navigator.userAgent.toLowerCase()) && 'ontouchstart' in document.documentElement);
function initialize() {
if ( !probablyPhone ) {
alert ("Your device is probably not a phone");
( function( $ ) {
$( '.call' ).css ( "text-decoration", "none" );
$( '.call' ).css ( "color", "black" );
$( '.call' ).css ( "cursor", "default" );
} )( jQuery );
}
}
</script>
</head>
<body onLoad="initialize();">
Please ring (some fictitious number in Australia): +61 3 9111 2222
</body>
</html>
Note that I also added some re-formatting of the link to make it appear to the user as if it's just ordinary text.
Here is a gist I created.
Just to finish this post/ answer, credit for writing succinct JavaScipt code for detecting a phone (based on the user agent and the ontouchstart event) goes to a fellow Melbournian rgb in this stackoverflow post
Here is a simple jquery-based solution which I developed to solve this problem. See code comments for explanation.
https://jsfiddle.net/az96o8Ly/
// Use event delegation, to catch clicks on links that may be added by javascript at any time.
jQuery(document.documentElement).on('click', '[href^="tel:"]', function(e){
try{
// These user-agents probably support making calls natively.
if( /Android|webOS|iPhone|iPad|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// Do nothing; This device probably supports making phone calls natively...
} else {
// Extract the phone number.
var phoneNumber = jQuery(this).attr('href').replace('tel:', '').trim();
// Tell the user to call it.
alert("Please call "+phoneNumber);
// Prevent the browser popup about unknown protocol tel:
e.preventDefault();
e.stopPropagation();
}
} catch(e){
console.log("Exception when catching telephone call click!", e);
}
});
My approach is similar to another approach above; there are a few considerations I take into account:
As we know, there is no good programmatic way to detect support. This is a rare case where we are forced to parse the UserAgent string.
This should be client side; there is no need for server side detection.
There are now desktop browsers that can handle tel: links; Chrome's behavior on the desktop is, at worst, to do nothing when clicked. At best, you can make a call with Google Voice.
Because doing nothing when clicked is Chrome's fallback behavior, we should use that behavior as a fallback on all browsers.
If your page takes responsibility for creating tel: links, it should take responsibility for all tel: links and disable autodetection in the browser.
With all of this in mind, I suggest first adding a meta tag to your <head>:
<meta name="format-detection" content="telephone=no"/>
Then, define a JavaScript function that parses the UserAgent and returns true if and only if we think the browser will not bring us to an error page when the link is clicked:
function hasTelSupport()
{
return /Chrome\/|Mobile( Safari)?\/|Opera M(in|ob)i\/|w(eb)?OSBrowser\/|Mobile\;|Tablet\;/.test(navigator.userAgent);
}
Then, call that function from the onclick attribute in your link:
Call Me
This will allow tel: links to be clicked on Chrome, Edge, iOS Safari, Android Browser, Blackberry, Dorothy, Firefox Mobile, IE Mobile, Opera Mini, Opera Mobile, and webOS. The links will do nothing when clicked on other devices or browsers.
Please use international format for your tel: links. In other words, the first characters should be a + and a country code.
Thanks to TattyFromMelbourne's post I am now using a pretty simple bit:
My button id="call" will make the phone call based on his "probablyphone" test function but also will scroll down to the contact info section either way giving the button a working use no matter what.
I aslo replaced the alert with an empty function, to remove the pop-up.
<a id="call" href="#contact">PHONE US</a>
$("#call").on('click', function() {
var probablyPhone = ((/iphone|android|ie|blackberry|fennec/).test(navigator.userAgent.toLowerCase()) && 'ontouchstart' in document.documentElement);
var link = "callto:15555555555";
if ( !probablyPhone ) {
window.alert = function() {};}
else{window.location.href = link;}
});
</script>
You can use css3 media queries to detect a mobile window and hide the link accordingly.
#media(max-width:640px){
.your-calling-link{
display:none;
}
}
Alternately, if you want to show the link and just disable click functionality, use jquery function:
screen.width
or
screen.innerWidth
and disable the click functionality on the link using
$('.your-link').off(click);
One way of handling this is to create two separate divs and use display:hidden.
Example:
<div class="mobile-desktop"><p>123-456-7890</p></div>
<div class="mobile-mobile">123-456-7890</div>
In your css set your mobile break points. This part is really up to you. Let's say
#media only screen (min-width: 768px){
.mobile-mobile {
display:none;
}
}
#media only screen (max-width: 767px){
.mobile-desktop{
display:none;
}
}
This should let you hide one div based on screen size. Granted 789 is just a number I picked, so pick a size you believe is mobile. You can find them online at like this site I found on Google or others like it. Lastly, this is just a quick css markup, you might have to tinker but the idea is there.
This way works without adding any more CSS.
Try replacing the a tag with something else like a span tag, but only for mobile browsers of course. Benefits are that you are not cloaking this a with CSS preventing default action while keeping it still as a link. It won't be a anymore, so you won't have to worry.
I've created an example to here. Bold phone there works this way, see code below.
I took piece of code from one of the respondent to define if browser is mobile. And you have to mark these links with class="tel" or find a way to determine if the href has "tel:" in it. JQuery is also required.
// define if browser is mobile, usually I use Anthony's Hand mobile detection library, but here is simple detection for clarity
var probablyPhone = ((/iphone|android|ie|blackberry|fennec/).test(navigator.userAgent.toLowerCase()) && 'ontouchstart' in document.documentElement);
if ( !probablyPhone ) {
// find all the A with "tel:" in it, by class name
$('a.tel').each(function(){
var span = document.createElement('span');
// SPAN inherits properties of A, you can also add STYLE or TITLE or whatever
span.innerHTML = this.innerHTML;
span.className = this.className;
// replace A with SPAN
this.parentNode.insertBefore(span, this);
this.parentNode.removeChild(this);
});
}
Input this into custom css and call it a day:
a.tel { color: #FFFFFF; cursor: default; /* no hand pointer */ }
Change your color as needed.
Cheers!
I am adding the following css through javascript when mobile device is detected.
pointer-events:none
The js code is:
var a = document.getElementById("phone-number");
if (Platform.isMobile()) // my own mobile detection function
a.href = "tel:+1.212.555.1212";
else
$(a).css( "pointer-events", "none" );
In my target site, all phone link markups are in this pattern:
111-222-3333. My solution is such simple:
function setPhoneLink() {
if (screen.width > 640) {
$("a[href^='tel:']").each(function(){
$(this).replaceWith($(this).text());
});
}
}
Device-width: mobile<640; tablet >=768 and <1024; desk >=1024.
Source: http://javascriptkit.com/dhtmltutors/cssmediaqueries2.shtml
Don't use the screen size as a requirement for that.
You can use CSS media query like this:
#media (pointer: fine) { /* this is for devices using a mouse, maybe a pen */
a[href^="tel:"] { /* select only "tel:" links */
pointer-events: none; /* avoid clicks on this element */
}
}
#media (pointer: coarse) { /* this works for mobile phones */
}
More info: https://developer.mozilla.org/en-US/docs/Web/CSS/#media/pointer
#media screen {.telephone {pointer-events: none;}}

possible to thwart browser fingerprinting by returning a bogus installed-fonts list?

Is it possible to write a program that masks the set of fonts installed on the computer, so the font list would appear "plain vanilla" and would not be of much value in creating a ~unique fingerprint? https://panopticlick.eff.org/
There is probably some support for that in some browsers, but with any browser you could intercept the winapi calls for enumerating the font list.
Basically you write a dll that will be loaded into the browser process, and then it will intercept the calls the browser will make to the OS when it will enumerate fonts. Just lookup which functions in windows are used for enumerating fonts, and fake them in your dll. (that could be some work though, because you will have to rewrite the font enumerating logic).
Also, some of the browsers may very well just read the registry to enumerate fonts, and not use the specialized fontfunctions, in that case you will have to intercept the registry-winapi functions, and make sure they report the font list that you want.
For loading your dll into the target process you could use Windows hooks, or use a .exe file editor to add your dll to import table of the browser's exe file. There is also a special place in the registry where if you add a dll there, it will be loaded to every process in the system. (then you'll have to check for browser process, and only intercept api calls then, so that not every program on your system will get the bogus font list).
Also, it is possible that a browser will run some plugin, or activex control, or java, or something like that in another process (chrome runs every tab in different processes for example), so I would check every process' parent, and if you see that it has been started by the browser, intercept the font list in that process also. That way, the target webpage won't be able to get the real font list through flash, plugins, java, or anything.
A good start to intercepting winapi calls can be found here: http://www.codeproject.com/KB/system/InterceptWinAPICalls.aspx
So this is a reliable way to do this, and although it can't be done in an hour, it's not overly complicated either.
Of course, this will not only make your font list bogus, it will also make the browser not see and be able to display the fonts that are not in the list.
And this all is valid for Windows of course, but there are surely similair ways to do this on other OSes.
Also, worth to note, I don't think a webpage can read the font list if you have disabled javascript and plugins(flash).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Font detector</title>
<style type="text/css" media="screen">
#font_detector_box{ visibility: hidden; }
#font_detector_box span.font{ padding: 0px; margin: 0px; border: none; font-size: 10px; letter-spacing: 1px; }
</style>
</head>
<body>
<h1>Font Detection Page</h1>
<p>This page is a sample for font detection tecniques</p>
<h2>List of fonts installed on your machine</h2>
<span id="font_list_display">
</span>
<!-- Invisible div -->
<div id="font_detector_box">
<span class="font family_Arial" style="font-family: Arial, Verdana !important">mmm</span>
<span class="font family_Comics_Sans_MS" style="font-family: Comic Sans MS, Arial !important">mmm</span>
<span class="font family_Georgia" style="font-family: Georgia, Arial !important">mmm</span>
<span class="font family_Helvetica" style="font-family: Helvetica, Verdana !important">mmm</span>
<span class="font family_Verdana" style="font-family: Verdana, Arial !important">mmm</span>
<span class="font family_Times_New_Roman" style="font-family: Times New Roman, Arial !important">mmm</span>
</div>
</body>
<script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
var fontMeasures = new Array( );
//Web safe
fontMeasures["Arial"] = new Array( "30px", "13px" );
fontMeasures["Comics_Sans_MS"] = new Array( "27px" , "14px" );
fontMeasures["Georgia"] = new Array( "33px" , "13px" );
fontMeasures["Helvetica"] = new Array( "30px" , "13px" );
fontMeasures["Verdana"] = new Array( "36px" , "12px" );
fontMeasures["Times_New_Roman"] = new Array( "27px" , "12px" );
var msg = "";
$( ".font" , "#font_detector_box" ).each( function( ){
var fontFamily = $( this ).attr( "class" ).toString( ).replace( "font " , "" ).replace( "family_" , "" );
var width = $( this ).css( "width" );
var height = $( this ).css( "height" );
//alert( width + height );
if( fontMeasures[fontFamily][0] === width && fontMeasures[fontFamily][1] === height ){
var family = fontFamily.replace( /_/g , " " );
msg += '<span class="font-family: '+ family + ';">' + family + '</span> <br/>';
}
});
$( "#font_list_display" ).html( msg );
</script>
</html>

Resources