IFrame get scroll position - javascript

I am scrolling a pdf file inside an Iframe and trying to access the scroll position but failed to do so. tried all the resources but they don't seem to work anymore. Any help is Greatly Appreciated.
const iframe = document.getElementById('iframe');
iframe.onload = function() {
console.log("IFrame Loaded")
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
iframeDoc.addEventListener('scroll', function() {
console.log("Scrolling Started")
console.log(iframeDoc.documentElement.scrollTop);
});
};

Related

How to open a link in a new tab without seeing the URL in new tab?

I've been trying many things to make this work but nothing has yet. How can I open a website in a new tab and have it not show the URL being used? I got this idea from this website. The new tabs URL shows up as about:blank. However, I've not been able to get it to work. I'm new to Javascript so go easy on me! Thanks!!!
This is what I've tried:
function NewTab() {
window.open(
"https://www.mywebsite.com", "_blank");
}
After digging through the website I was able to find the JS that opens a new tab "without" exposing the URL to the user:
var urlObj = new window.URL(window.location.href);
var url = "https://tam-shellshock.franklinformulas.com"
if (url) {
var win;
document.querySelector('a').onclick = function() {
if (win) {
win.focus();
} else {
win = window.open();
win.document.body.style.margin = '0';
win.document.body.style.height = '100vh';
var iframe = win.document.createElement('iframe');
iframe.style.border = 'none';
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.margin = '0';
iframe.src = url;
win.document.body.appendChild(iframe);
}
};
}
<a>Press here</a>

JavaScript: embedded YouTube video not playing in modal popup

I have the following code which looks at a specific css class .vma_iFramePopup and from it, takes the link stored in the src. And then loads that in a modal popup.
$(document).ready(function () {
$(".vma_overlay").click(function (event) {
var $videoSrcOriginal = $(event.target).siblings('.vma_iFramePopup').attr("src");
// Check if the embedded youtube url has any attributes appended
// by looking for a '?' in the url.
// If one is found, append our autoplay attribute using '&',
// else append it with '?'.
if ($videoSrcOriginal.indexOf('?') > -1) {
var $videoSrc = $videoSrcOriginal
// when the modal is opened autoplay it
$('#vma_ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay
var $videoSrcAuto = $videoSrc + "&autoplay=1&mute=1";
$("#vma_video").attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
})
} else {
var $videoSrc = $(".vma_iFramePopup").attr("src");
// when the modal is opened autoplay it
$('#vma_ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay
var $videoSrcAuto = $videoSrc + "?autoplay=1&mute=1";
$("#vma_video").attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
})
}
// stop playing the youtube video when modal is closed
$('#vma_ModalBox').on('hide.bs.modal', function (e) {
$("#vma_video").attr('src', $videoSrc);
$('body').removeClass("modalyt");
})
});
});
I was informed that the videos are not playing in the modal. The modal when loaded is empty.
When I check the browser console, I am not seeing any relevant errors.
When I check the iframe inside my modal popup I see that it says
src(unknown)
in the src element:
<iframe class="embed-responsive-item" width="80%" height="80%" src(unknown) id="vma_video" allowfullscreen="" data-gtm-yt-inspected-9256558_25="true">></iframe>
I have not been able to identify why this is happening?
I 've tried fiddling on the live website with a very slight variation of your code and it seems to work:
$('.vma_overlay').on('click', function() {
var $videoSrcOriginal = $(this).siblings('.vma_iFramePopup').attr("src");
if ($videoSrcOriginal.indexOf('?') > -1) {
$('#vma_ModalBox').show();
var $videoSrcAuto = $videoSrcOriginal + "&autoplay=1&mute=1";
$('#vma_ModalBox #vma_video').attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
}
});
It turns out the solution in this particular case was to replace:
$(document).ready(function () {
with:
window.onload = function () {
For some reason specific to our setup, the jquery way of getting document ready was not firing.

Change the URL path of parent window in the background without closing the iframe

I am able to change the parent window from iframe by clicking a link, but as soon as I click on the link, the iframe is also gone. Is there any way to change the path of parent window from iframe in background without closing the iframe?
var iframe = document.createElement('iframe');
iframe.onload = function(){
var link=document.createElement("a");
link.appendChild(document.createTextNode("Link"));
link.href = '#';
document.body.appendChild(link);
var s = document.createElement("script");
s.innerHTML = "window.addEventListener('click', function(event) {" +
"window.postMessage('testMsg', '*');" +
"}, false);";
document.head.appendChild(s);
}
iframe.src = 'http://example.org';
document.body.appendChild(iframe);
window.addEventListener('message', function(event) {
window.location.href = "http://jsfiddle.net";}, false );
window.top.location.href = "http://www.example.com";
Try out This one, Man...!!

Print PDF directly from JavaScript

I am building a list of PDFs in HTML. In the list I'd like to include a download link and a print button/link. Is there some way to directly open the Print dialog for the PDF without the user seeing the PDF or opening a PDF viewer?
Some variation of downloading the PDF into a hidden iframe and triggering it to print with JavaScript?
Based on comments below, it no longer works in modern browsers
This question demonstrates an approach that might be helpful to you: Silent print an embedded PDF
It uses the <embed> tag to embed the PDF in the document:
<embed
type="application/pdf"
src="path_to_pdf_document.pdf"
id="pdfDocument"
width="100%"
height="100%" />
Then you call the .print() method on the element in Javascript when the PDF is loaded:
function printDocument(documentId) {
var doc = document.getElementById(documentId);
//Wait until PDF is ready to print
if (typeof doc.print === 'undefined') {
setTimeout(function(){printDocument(documentId);}, 1000);
} else {
doc.print();
}
}
You could place the embed in a hidden iframe and print it from there, giving you a seamless experience.
Here is a function to print a PDF from an iframe.
You just need to pass the URL of the PDF to the function. It will create an iframe and trigger print once the PDF is load.
Note that the function doesn't destroy the iframe. Instead, it reuses it each time the function is call. It's hard to destroy the iframe because it is needed until the printing is done, and the print method doesn't has callback support (as far as I know).
printPdf = function (url) {
var iframe = this._printIframe;
if (!this._printIframe) {
iframe = this._printIframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function() {
setTimeout(function() {
iframe.focus();
iframe.contentWindow.print();
}, 1);
};
}
iframe.src = url;
}
You can use Print.js (npm install print-js). It's 128kB unpacked and you can find the docs at http://printjs.crabbly.com/.
It doesn't print on IE though, in those cases you'll have to download the PDF instead.
$http({
url: "",
method: "GET",
headers: {
"Content-type": "application/pdf"
},
responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
var pdfFile = new Blob([data], {
type: "application/pdf"
});
var pdfUrl = URL.createObjectURL(pdfFile);
//window.open(pdfUrl);
printJS(pdfUrl);
//var printwWindow = $window.open(pdfUrl);
//printwWindow.print();
}).error(function (data, status, headers, config) {
alert("Sorry, something went wrong")
});
https://github.com/mozilla/pdf.js/
for a live demo http://mozilla.github.io/pdf.js/
it's probably what you want, but I can't see the point of this since modern browsers include such functionality, also it will run terribly slow on low-powered devices like mobile devices that, by the way, have their own optimized plugins and apps.
Cross browser solution for printing pdf from base64 string:
Chrome: print window is opened
FF: new tab with pdf is opened
IE11: open/save prompt is opened
.
const blobPdfFromBase64String = base64String => {
const byteArray = Uint8Array.from(
atob(base64String)
.split('')
.map(char => char.charCodeAt(0))
);
return new Blob([byteArray], { type: 'application/pdf' });
};
const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // or however you want to check it
const printPDF = blob => {
try {
isIE11
? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
: printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
} catch (e) {
throw PDFError;
}
};
printPDF(blobPdfFromBase64String(base64String))
BONUS - Opening blob file in new tab for IE11
If you're able to do some preprocessing of the base64 string on the server you could expose it under some url and use the link in printJS :)
I used this function to download pdf stream from server.
function printPdf(url) {
var iframe = document.createElement('iframe');
// iframe.id = 'pdfIframe'
iframe.className='pdfIframe'
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function () {
setTimeout(function () {
iframe.focus();
iframe.contentWindow.print();
URL.revokeObjectURL(url)
// document.body.removeChild(iframe)
}, 1);
};
iframe.src = url;
// URL.revokeObjectURL(url)
}
You can download the pdf file using fetch, and print it with Print.js
fetch("url").then(function (response) {
response.blob().then(function (blob) {
var reader = new FileReader();
reader.onload = function () {
//Remove the data:application/pdf;base64,
printJS({
printable: reader.result.substring(28),
type: 'pdf',
base64: true
});
};
reader.readAsDataURL(blob);
})
});
function printFile(url) {
const iframe = document.createElement('iframe');
iframe.src = url;
iframe.style.display = 'none';
document.body.appendChild(iframe);
// Use onload to make pdf preview work on firefox
iframe.onload = () => {
iframe.contentWindow.focus();
iframe.contentWindow.print();
};
}
It will be easy this way:
function PrintPdf (pdf) {
var iframe = document.createElement('iframe');
iframe.style.display = "none";
iframe.src = pdf;
document.body.appendChild(iframe);
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
Simplification of #Nicolas BADIA's answer:
function printPDF (url)
{
let pdfFrame = document.body.appendChild(document.createElement('iframe'));
pdfFrame.style.display = 'none';
pdfFrame.onload = () => (void pdfFrame.contentWindow.print());
pdfFrame.src = url;
}

Stop all playing iframe videos on click a link javascript

I have a list of iframe videos in my webpage.
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe>
Stop all videos
I need to stop all playing iframe videos on click the link Stop all videos. How can i do that?
Try this way,
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
$('.close').click(function(){
$('iframe').attr('src', $('iframe').attr('src'));
});
});
</script>
Reloading all iframes just to stop them is a terrible idea. You should get advantage of what comes with HTML5.
Without using YouTube's iframe_API library; you can simply use:
var stopAllYouTubeVideos = () => {
var iframes = document.querySelectorAll('iframe');
Array.prototype.forEach.call(iframes, iframe => {
iframe.contentWindow.postMessage(JSON.stringify({ event: 'command',
func: 'stopVideo' }), '*');
});
}
stopAllYouTubeVideos();
which will stop all YouTubes iframe videos.
You can use these message keywords to start/stop/pause youtube embdded videos:
stopVideo
playVideo
pauseVideo
Check out the link below for the live demo:
https://codepen.io/mcakir/pen/JpQpwm
PS-
YouTube URL must have ?enablejsapi=1 query parameter to make this solution work.
This should stop all videos playing in all iframes on the page:
$("iframe").each(function() {
var src= $(this).attr('src');
$(this).attr('src',src);
});
Stopping means pausing and setting the video to time 0:
$('iframe').contents().find('video').each(function ()
{
this.currentTime = 0;
this.pause();
});
This jquery code will do exactly that.
No need to replace the src attribute and reload the video again.
Little function that I am using in my project:
function pauseAllVideos()
{
$('iframe').contents().find('video').each(function ()
{
this.pause();
});
$('video').each(function ()
{
this.pause();
});
}
Here's a vanilla Javascript solution in 2019
const videos = document.querySelectorAll('iframe')
const close = document.querySelector('.close')
close.addEventListener('click', () => {
videos.forEach(i => {
const source = i.src
i.src = ''
i.src = source
})
})
I edited the above code a little and the following worked for me.......
<script>
function stop(){<br/>
var iframe = document.getElementById('myvid');<br/>
var iframe1 = document.getElementById('myvid1');<br/>
var iframe2 = document.getElementById('myvid2');<br/>
iframe.src = iframe.src;<br/>
iframe1.src=iframe1.src;<br/>
iframe2.src=iframe2.src;<br/>
}<br/>
</script>
$("#close").click(function(){
$("#videoContainer")[0].pause();
});
In jQuery you can stop iframe or html video, by using below code.
This will work for single or multiple video on the same page.
var videos = document.querySelectorAll('iframe');
$(".video-modal .fa-times").on("click", function () {
videos.forEach(i => {
let source = i.src;
i.src = '';
i.src = source;
});
$(".video-modal").css("display", "none");
return false;
});
})
Reload all iframes again to stop videos
Stop all videos
function stop(){
var iframe = document.getElementById('youriframe');
iframe.src = iframe.src;
}
You can modify this code with an iteration
/**
* Stop an iframe or HTML5 <video> from playing
* #param {Element} element The element that contains the video
*/
var stopVideo = function ( element ) {
var iframe = element.querySelector( 'iframe');
var video = element.querySelector( 'video' );
if ( iframe ) {
var iframeSrc = iframe.src;
iframe.src = iframeSrc;
}
if ( video ) {
video.pause();
}
};
OWNER: https://gist.github.com/cferdinandi/9044694
also posted here (by me): how to destroy bootstrap modal window completely?

Categories