How to show message if Adobe Reader is not installed? - javascript

I have embeded PDF on my page for which, using "<iFrame>" I am calling a HTML page which contains the <Object> tag with in that there is an <embed> tag which embeds the PDF and a tag which shows up if there is not Adobe Reader installed.
On Firefox, Chrome and IE 11 if the there is a PDF reader installed, it will show only the PDF but when there is no reader istalled it shows the message in <p> tag "install the Adobe reader".
My Issue is :- in IE10, even if the Adobe reader is installed it shows the message "install the Adobe reader" in <p> tag. Please suggest how to hide the message if Adobe Reader is installed and the message should show only if PDF Reader is not installed.
Here is my CODE:
Iframe code from where PDF page is being called:
<div id="pdf">
<iframe id="pdfIframe" name="pdfIframe" src="pdfView.html" style="width: 100%; height: 100%;" scrolling="auto" frameborder="1">
Your browser doesn't support inline frames.
</iframe>
</div>
PDF page Code:
<body>
<style>
html, body, #blankPane {
height: 100%;
margin: 0;
padding: 0;
}
#blankPane p {
font-weight: bold;
line-height: 30px;
height: auto;
width: 98%;
margin: 0 auto;
color: #bc0000;
}
#blankPane * {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<div id="blankPane" class="overflowHidden">
<object data="lorem.pdf" type="application/pdf">
<p>
It appears you don't have Adobe Reader or PDF support in this web browser.
<br />
Click here to download the PDF OR Click here to install Adobe Reader
</p>
<embed id="pdfDocument" src="lorem.pdf" type="application/pdf" />
</object>
</div>
Please suggest!!!

You can detect which version of Adobe Acrobat that is installed with a javascript like the one below, or you can use FlexPaper to display your document if you prefer not to rely on Adobe Acrobat
var getAcrobatInfo = function() {
var getBrowserName = function() {
return this.name = this.name || function() {
var userAgent = navigator ? navigator.userAgent.toLowerCase() : "other";
if(userAgent.indexOf("chrome") > -1) return "chrome";
else if(userAgent.indexOf("safari") > -1) return "safari";
else if(userAgent.indexOf("msie") > -1) return "ie";
else if(userAgent.indexOf("firefox") > -1) return "firefox";
return userAgent;
}();
};
var getActiveXObject = function(name) {
try { return new ActiveXObject(name); } catch(e) {}
};
var getNavigatorPlugin = function(name) {
for(key in navigator.plugins) {
var plugin = navigator.plugins[key];
if(plugin.name == name) return plugin;
}
};
var getPDFPlugin = function() {
return this.plugin = this.plugin || function() {
if(getBrowserName() == 'ie') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
}
else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF');
}
}();
};
var isAcrobatInstalled = function() {
return !!getPDFPlugin();
};
var getAcrobatVersion = function() {
try {
var plugin = getPDFPlugin();
if(getBrowserName() == 'ie') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if(plugin.version) return parseInt(plugin.version);
return plugin.name
}
catch(e) {
return null;
}
}
//
// The returned object
//
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
Example of how to call these functions:
var info = getAcrobatInfo();
alert(info.browser+ " " + info.acrobat + " " + info.acrobatVersion);

Related

Open a image of a Google Doc in in another window

I have a Google Doc with images. I would like to open a selected image in a page in another window (the google doc is a role playing game scenario and I want to show the image to my players on a second screen).
I have created a sidebar with a google script and I am able to show the selected image in this sidebar.
Now, I don't know how to open a new window (or connect a existing window) and send the image data to this window.
I start by trying to use the "PresentationRequest", but I have the error "PresentationRequest is not defined" on the init...
presentationRequest = new PresentationRequest('receiver.html');
My source :
https://developers.google.com/web/updates/2018/04/present-web-pages-to-secondary-attached-displays
For information (and if it helps someone) how I send the image to the sidebar page:
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
if (selection) {
var elements = selection.getRangeElements();
var e = elements[0].getElement();
if (e.getType() == DocumentApp.ElementType.INLINE_IMAGE) {
var blobImg = e.asInlineImage().getBlob();
return 'data:' + blobImg.getContentType() + ';base64,' + Utilities.base64Encode(blobImg.getBytes());
}
}
The HTML code :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style type="text/css">
.tailMax {
max-width: 260px;
max-height: 260px;
}
.centre {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<form id="formJdr">
<div style="padding-bottom: 10px;">
<button type="button" id="btnAffImg" onclick="google.script.run.withSuccessHandler(afficheImg).selectImg()">Afficher</button>
<label id="lblImg">Sélectionnez une image</label>
</div>
<img id="img" class="tailMax centre"/>
</form>
<script>
function afficheImg(valeur) {
if (typeof value === "string"){
// Message
afficheMessage(valeur);
}
else {
try {
// Image to show
afficheMessage("");
document.getElementById("img").src = valeur;
}
catch(error) {
afficheMessage(error);
}
}
}
function afficheMessage(message) {
document.getElementById("lblImg").innerHTML = message;
}
</script>
</body>
</html>
I use a Chrome browser.
Do you think it is possible?
Modify your try statement as following:
try {
// Image to show
afficheMessage("");
var image=document.getElementById("img");
image.src = valeur;
var w = window.open("", '_blank');
w.document.write(image.outerHTML);
}
var w = window.open("", '_blank'); w.document.write(image.outerHTML); allows you to open a new window and then write the image as bytearray into it.
Ok, with the help of Ziganotschka, I update my javascript code for this.
Now I can change the image in the new window.
Just some improvements to make on the opening of this window and it will be good.
<script>
var affichage;
function afficheImg(valeur) {
if (typeof value === "string"){
afficheMessage(valeur);
}
else {
try {
afficheMessage("");
var image = document.getElementById("img");
image.src = valeur;
affichage.document.body.innerHTML = "";
affichage.document.write(image.outerHTML);
}
catch(error) {
afficheMessage(error);
}
}
}
function afficheMessage(message) {
document.getElementById("lblImg").innerHTML = message;
}
window.onload = function() {
affichage = window.open("", '_blank');
</script>

How to read a local file in JQuery or JavaScript?

I have an HTML file, which I want to read and append as HTML. I have tried the below codes but these codes are not working.
Approach 1:
var file = "abc.html";
var str = "";
var txtFile = new File(file);
txtFile.open("r");
while (!txtFile.eof) {
// read each line of text
str += txtFile.readln() + "\n";
}
$('#myapp').html(str);
Approach 2:
var file = "abc.html";
var rawFile = new XMLHttpRequest();
alert('33333333');
rawFile.open("GET", file, false);
alert('44444');
rawFile.onreadystatechange = function () {
alert('5555555555');
if (rawFile.readyState === 4) {
alert('66666666666');
alert(rawFile.readyState);
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
$('#myapp').html(allText);
alert(allText);
}
}
}
rawFile.send(null);
In Approach 2, it not going into the onreadystatechange method.
I thought another approach that I will use all the abc.html file content as a string variable and do similar $('#myapp').html(allText);, but this looks very bad approach because later I need to do the same for other 10-15 files. So Could you guys help me out?
Note: My application is running in offline mode means I cannot use the internet.
I have tried this solution, but its also not working.
It is not possible as JavaScript is frontend framework and it doesn't have access to local file system.
But you can do diffrent method.
-> you can serve that file in a local server and use http request with any backend framework.
I think you can adapt this pen to use as you wish:
https://codepen.io/alvaro-alves/pen/wxQwmg?editors=1111
CSS:
#drop_zone {
width: 100px;
height: 100px;
background: #000;
background-repeat: no-repeat;
background-size: 100px 100px;
opacity: 0.5;
border: 1px #000 dashed;
}
HTML:
<html>
<body>
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
</div>
</body>
</html>
JS:
//drop handler do XML
function dropHandler(ev) {
ev.preventDefault();
var file, reader, parsed, emit, x, endereco;
if (ev.dataTransfer.items) {
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
if (ev.dataTransfer.items[i].kind === 'file') {
file = ev.dataTransfer.items[i].getAsFile();
reader = new FileReader();
reader.onload = function() {
parsed = new DOMParser().parseFromString(this.result, "text/xml");
console.log(parsed);
};
reader.readAsText(file);
console.log('... file[' + i + '].name = ' + file.name);
}
}
}
removeDragData(ev)
}
function dragOverHandler(ev) {
ev.preventDefault();
}
function removeDragData(ev) {
if (ev.dataTransfer.items) {
ev.dataTransfer.items.clear();
} else {
ev.dataTransfer.clearData();
}
}
You will just to handle the result.

Why isn't document.execCommand causing the clipboard to populate?

I have the following HTML:
<td class="pn">
<span class="copyable">410-555-1234</span>
<span title="Click to copy" class="clipboard">📋</span>
<form class="pn-copy-form">
<input class="pn-copy" type="text" value="+14105551234" />
</form>
</td>
When the user clicks on the clipboard icon, I would like to populate the contents of the user's system clipboard with "+14105551234". However, I notice that nothing populates. Here's the Javascript I'm using, placed at the bottom of the same page:
var evHandler = function(clipboardElem) {
return function() {
var pnCopy = clipboardElem.parentNode.querySelector('.pn-copy');
if (pnCopy === null) {
return;
}
pnCopy.select();
try {
result = document.execCommand('copy');
if (result === false) {
throw new Error("Could not copy value: " + pnCopy.value);
}
} catch (e) {
console.error(e);
alert("Couldn't copy text, sorry. Here it is: " + pnCopy.value);
}
console.log("Copied "+ pnCopy.value + " to the clipboard");
pnCopy.blur();
};
}
var clipboards = document.querySelectorAll('.clipboard');
for (var i = 0; i < clipboards.length; i++) {
var clipboard = clipboards[i];
clipboard.addEventListener('click', evHandler(clipboard));
}
I'm hiding the form, since I don't want it to appear on the page.
.pn-copy {
display: none;
}
Why isn't the clipboard populating? Does click-to-copy not work on localhost, or not work on unencrypted HTTP?
The form needs to be "visible," though that definition is loose, and I think is roughly "not display:none". Without that in place, .select() selects no text. I had success with the following CSS, which leaves the input "visible" but placed 3000 pixels off screen.
/* the input has to be "visible", if you use display: none copy won't work. */
.pn-copy-form {
position: absolute;
height: 1px;
left: -3000px;
}

Image upload on file chosen not on submit form , [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a HTML form where the user can upload an image in the input field and it works fine but the image is uploaded when the form is submitted.
Is there a way where I can get the image to upload to the TMP directory when the file is chosen and the user is still filling out the form then when the user submits the form it can be moved to the actual file directory. This would make for a better user experience and especially people with slow internet connections would benefit from this as it would utilise the users time for effectively and efficiently.
I am not sure exactly but I think this would need some sort of jQuery/Ajax solution to upload the image mid form entry then use PHP to transfer the file from the TMP to the actual directory.
As Diodeus suggested, putting the form in an iframe would prevent it from posting in the current page frame and allow users to work on other form items. A solution more to what you were expecting would be using an AJAX request. You could look into the HTML5 API, there are many different already-built solutions and many tutorials.
Here's a simple example taken from this demo at html5demos.com
<title>Drag and drop, automatic upload</title>
<style>
#holder { border: 10px dashed #ccc; width: 300px; min-height: 300px; margin: 20px auto;}
#holder.hover { border: 10px dashed #0c0; }
#holder img { display: block; margin: 10px auto; }
#holder p { margin: 10px; font-size: 14px; }
progress { width: 100%; }
progress:after { content: '%'; }
.fail { background: #c00; padding: 2px; color: #fff; }
.hidden { display: none !important;}
</style>
<article>
<div id="holder">
</div>
<p id="upload" class="hidden"><label>Drag & drop not supported, but you can still upload via this input field:<br><input type="file"></label></p>
<p id="filereader">File API & FileReader API not supported</p>
<p id="formdata">XHR2's FormData is not supported</p>
<p id="progress">XHR2's upload progress isn't supported</p>
<p>Upload progress: <progress id="uploadprogress" min="0" max="100" value="0">0</progress></p>
<p>Drag an image from your desktop on to the drop zone above to see the browser both render the preview, but also upload automatically to this server.</p>
</article>
<script>
var holder = document.getElementById('holder'),
tests = {
filereader: typeof FileReader != 'undefined',
dnd: 'draggable' in document.createElement('span'),
formdata: !!window.FormData,
progress: "upload" in new XMLHttpRequest
},
support = {
filereader: document.getElementById('filereader'),
formdata: document.getElementById('formdata'),
progress: document.getElementById('progress')
},
acceptedTypes = {
'image/png': true,
'image/jpeg': true,
'image/gif': true
},
progress = document.getElementById('uploadprogress'),
fileupload = document.getElementById('upload');
"filereader formdata progress".split(' ').forEach(function (api) {
if (tests[api] === false) {
support[api].className = 'fail';
} else {
// FFS. I could have done el.hidden = true, but IE doesn't support
// hidden, so I tried to create a polyfill that would extend the
// Element.prototype, but then IE10 doesn't even give me access
// to the Element object. Brilliant.
support[api].className = 'hidden';
}
});
function previewfile(file) {
if (tests.filereader === true && acceptedTypes[file.type] === true) {
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result;
image.width = 250; // a fake resize
holder.appendChild(image);
};
reader.readAsDataURL(file);
} else {
holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size/1024|0) + 'K' : '');
console.log(file);
}
}
function readfiles(files) {
debugger;
var formData = tests.formdata ? new FormData() : null;
for (var i = 0; i < files.length; i++) {
if (tests.formdata) formData.append('file', files[i]);
previewfile(files[i]);
}
// now post a new XHR request
if (tests.formdata) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/devnull.php');
xhr.onload = function() {
progress.value = progress.innerHTML = 100;
};
if (tests.progress) {
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
progress.value = progress.innerHTML = complete;
}
}
}
xhr.send(formData);
}
}
if (tests.dnd) {
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
readfiles(e.dataTransfer.files);
}
} else {
fileupload.className = 'hidden';
fileupload.querySelector('input').onchange = function () {
readfiles(this.files);
};
}
</script>
This creates a zone to drop a file (instead of a browse button) and initiate the file upload when the drag and drop event occurs. It will do it asynchronously and allow the page contents to be interacted with as normal while the transfer proceeds in the background. There is an important thing in this example to change, however. This line:
xhr.open('POST', '/devnull.php');
Should be changed to a code file in your environment/server that will process the file upload data and save or process the file however you need. This script merely acts as a front-end to that script. Another thing to remember is the HTML5 File API is still a modern-browser-only type of thing; it's well supported in current browsers, but older ones are out of luck. If you need to have them supported, you should look for another solution.

Using Google Text-To-Speech in Javascript

I need to play Google text-to-speech in JavaScript.
The idea is to use the web service:
http://translate.google.com/translate_tts?tl=en&q=This%20is%20just%20a%20test
And play it on a certian action, e.g. a button click.
But it seems that it is not like loading a normal wav/mp3 file:
<audio id="audiotag1" src="audio/example.wav" preload="auto"></audio>
<script type="text/javascript">
function play() {
document.getElementById('audiotag1').play();
}
</script>
How can I do this?
Another option now may be HTML5 text to speech, which is in Chrome 33+ and many others.
Here is a sample:
var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);
With this, perhaps you do not need to use a web service at all.
Here is the code snippet I found:
var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();
You can use the SpeechSynthesisUtterance with a function like say:
function say(m) {
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[10];
msg.voiceURI = "native";
msg.volume = 1;
msg.rate = 1;
msg.pitch = 0.8;
msg.text = m;
msg.lang = 'en-US';
speechSynthesis.speak(msg);
}
Then you only need to call say(msg) when using it.
Update: Look at Google's Developer Blog that is about Voice Driven Web Apps Introduction to the Web Speech API.
Very easy with responsive voice. Just include the js and voila!
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<input onclick="responsiveVoice.speak('This is the text you want to speak');" type='button' value='🔊 Play' />
I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:
const listenBtn = document.getElementById('myvoice');
listenBtn.addEventListener('click', (e) => {
e.preventDefault();
const msg = new SpeechSynthesisUtterance(
"Hello, hope my code is helpful"
);
window.speechSynthesis.speak(msg);
});
<button type="button" id='myvoice'>Listen to me</button>
The below JavaScript code sends "text" to be spoken/converted to mp3 audio to google cloud text-to-speech API and gets mp3 audio content as response back.
var text-to-speech = function(state) {
const url = 'https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=GOOGLE_API_KEY'
const data = {
'input':{
'text':'Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets.'
},
'voice':{
'languageCode':'en-gb',
'name':'en-GB-Standard-A',
'ssmlGender':'FEMALE'
},
'audioConfig':{
'audioEncoding':'MP3'
}
};
const otherparam={
headers:{
"content-type":"application/json; charset=UTF-8"
},
body:JSON.stringify(data),
method:"POST"
};
fetch(url,otherparam)
.then(data=>{return data.json()})
.then(res=>{console.log(res.audioContent); })
.catch(error=>{console.log(error);state.onError(error)})
};
Run this code it will take input as audio(microphone) and convert into the text than audio play.
<!doctype HTML>
<head>
<title>MY Echo</title>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.1/css/font-awesome.min.css" />
<style type="text/css">
body {
font-family: verdana;
}
#result {
height: 100px;
border: 1px solid #ccc;
padding: 10px;
box-shadow: 0 0 10px 0 #bbb;
margin-bottom: 30px;
font-size: 14px;
line-height: 25px;
}
button {
font-size: 20px;
position: relative;
left: 50%;
}
</style>
Speech to text converter in JS
var r = document.getElementById('result');
function startConverting() {
if ('webkitSpeechRecognition' in window) {
var speechRecognizer = new webkitSpeechRecognition();
speechRecognizer.continuous = true;
speechRecognizer.interimResults = true;
speechRecognizer.lang = 'en-IN';
speechRecognizer.start();
var finalTranscripts = '';
speechRecognizer.onresult = function(event) {
var interimTranscripts = '';
for (var i = event.resultIndex; i < event.results.length; i++) {
var transcript = event.results[i][0].transcript;
transcript.replace("\n", "<br>");
if (event.results[i].isFinal) {
finalTranscripts += transcript;
var speechresult = finalTranscripts;
console.log(speechresult);
if (speechresult) {
responsiveVoice.speak(speechresult, "UK English Female", {
pitch: 1
}, {
rate: 1
});
}
} else {
interimTranscripts += transcript;
}
}
r.innerHTML = finalTranscripts + '<span style="color:#999">' + interimTranscripts + '</span>';
};
speechRecognizer.onerror = function(event) {};
} else {
r.innerHTML = 'Your browser is not supported. If google chrome, please upgrade!';
}
}
</script>
</body>
</html>

Categories