Like many programs flash their window on the taskbar / dock to alert the user to switch to the program,
Is it possible to flash the Browser window using Javascript? (FireFox-only scripts are also welcome)
This is useful for web-based Chat / Forum / Community-based software where there is lots of real-time activity.
#Hexagon Theory: Why would you ever rewrite the whole head element just to change the value of one element in the head? Your solution is horribly inefficient on multiple levels.
<html>
<head>
<link rel="icon" href="on.png" type="image/png" id="changeMe" />
<script type="text/javascript" src="flash.js"></script>
</head>
<body>
</body>
</html>
flash.js:
function Flasher(speed) {
var elem = document.getElementById('changeMe');
this.timer = setTimeout(function() {
elem.href = elem.href == 'on.png' ? 'off.png' : 'on.png';
}, speed);
this.stop = function() { clearTimeout(this.timer); }
}
/* sample usage
*
* var flasher = new Flasher(1000);
* flasher.stop();
*/
It didn't really have to be a class but it helped keep the global namespace clean. That's untested but if simply changing the href doesn't work for some reason, clone the link node, change the href and replace the old link with the cloned one.
At this point, it seems only causing an alert dialog to pop up does the trick... this seems a bit too intrusive, I feel, particularly given the use you're trying to put it to. Instead of causing it to flash, though, you could modify document.title to grab the user's attention, either by prepending some signal (perhaps the string "NEW!") to the site's name, and then using an interval to constantly change it to "", which would then give a nice little "flashing" illusion.
Bare-bones example:
<html>
<head>
<title>Chat System</title>
<script>
var timer, old_t = document.title, blink_amount = 5, cur_b = 0;
function notify()
{
cur_b = 0;
timer = setInterval(function()
{
if (cur_b < blink_amount * 2)
{
cur_b++;
document.title = (document.title.indexOf('NEW! ') != -1) ? old_t : 'NEW! ' + old_t;
}
else
{
clearInterval(timer);
}
}, 600);
}
notify();
// From here, it's just a matter of calling the
// notify() function whenever you detect a new message.
</script>
</head>
<body>
</body>
</html>
Hey, another interesting solution to this question hit me just now. Why not really grab the user's attention by making the icon flash in their browser? You could, for example, make two icons (on.png and off.png in my example below) and repeatedly swap them out to really catch a user's eye. The following is a bare-bones implementation; do keep in mind that you will need to reference this script remotely or put it in the body of the page because it uses a method that repeatedly replaces the content of the <head> tag. Give it a try, though; I rather like the simplicity of it.
page.html:
<html>
<head>
<link rel="icon" href="on.png" type="image/png" />
<script type="text/javascript" src="flash.js"></script>
</head>
<body>
</body>
</html>
flash.js:
var timer, speed = 175;
function flash()
{
head_html = document.getElementsByTagName('head')[0].innerHTML;
if (head_html.indexOf('href="on.png"') != -1)
document.getElementsByTagName('head')[0].innerHTML = head_html.replace('on.png', 'off.png');
else
document.getElementsByTagName('head')[0].innerHTML = head_html.replace('off.png', 'on.png');
timer = setTimeout('flash()', speed);
}
function kill_flash() {clearTimeout(timer);}
flash();
Mozilla previously had Window.getAttention() but by 2018 no browsers were listed supporting it. https://web.archive.org/https://developer.mozilla.org/en-US/docs/Web/API/Window/getAttention
Its behavior:
Windows, the taskbar button for the window flashes
Linux, some window managers flash the taskbar button, others focus the window immediately
Macintosh, the icon in the upper right corner of the desktop flashes
Window.Focus() should do it on Windows, not sure on other platforms though. You might find it brings the Window to the foreground if it's minimised though, which would be very annoying :)
Related
I've spent nearly 2 days googling and trying lots of example (even here in StackOverflow), and I don't find any way to fire the event "afterprint". It seems dead. I've found some fiddle, where it works, and when I try to reproduce on my system, it doesn't.
I am not sure what I'm doing wrong.
Here is the code I want to use:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Printing</title>
</head>
<body>
<button id="myButton2" onClick="printPage('http://localhost/~user/testPDF.pdf')">Print Me 2</button><br>
<script type="text/javascript">
function closePrint () {
console.log("Ciao");
document.body.removeChild(this.__container__);
}
function printPage (sURL) {
var myButton = document.getElementById("myButton2");
myButton.disabled=true;
var printFrame = document.createElement("iframe");
printFrame.id = "printPDF2";
printFrame.style.display = 'none';
printFrame.src = sURL;
printFrame.onload = function() {
printFrame.contentWindow.addEventListener('afterprint', function(evt) {
console.log("yellow");
document.body.removeChild(iframe)
});
this.contentWindow.__container__ = this;
this.contentWindow.onbeforeunload = closePrint;
this.contentWindow.onafterprint = closePrint;
this.contentWindow.focus(); // Required for IE
this.contentWindow.print();
}
document.body.appendChild(printFrame);
}
</script>
</body>
</html>
I've tried also with the MediaDetect. And it doesn't work... (I used these links for inspiration: https://jsfiddle.net/5qbc1pzj/ and https://jsfiddle.net/anhhnt/nj851e52/) the JS console is empty... I get no "Ciao" or "yellow"...
I'm using a simple Apache server, and using the latest IE Edge (103.0.1264.62).
I am out of idea, could someone give me an idea, where to look at?
Thank you in advance.
Kind regards,
Alessandro
It doesn't work because detecting the print events only work for HTML-documents. The MIME type for PDF windows is application/pdf so it doesn't work. The events that are available on the window are not available to the <embed> like tags, as they are handled by the browser's default application for the type. Although the event occurs here, it is not bubbled back to the window. For more information, you can refer to this answer.
The only solution to this seems to create your own PDF viewer. For example, you can use PDF.js.
I created an account a very long time ago but I never really use it, as I always manage to find the answers to my questions in already solved threads. So, this is the first time since I'm working on my current program that I was not able to find a working answer on SO. However, if I simply missed it, please be nice to me ^^
A bit of context that may explain why I can't manage to apply any given solution despite many threads exists about this... I am doing:
A HTA Interface
With an iframe to a local text file
And a link to a js file that I want to use to refresh the iframe every 500 ms.
The goal is to make a chat; people can write on the text file and it automatically appears on the HTA interface.
I don't know ANYTHING about JS, frankly. So I found here that piece of code to refresh the iframe.
window.setInterval(function() {
document.getElementById('chatbox').contentWindow.location.reload();
}, 500);
It works, but upon refreshing the iframe, it scrolls back to the top; which makes the chat unreadable, as you can guess. Many solutions that I've read on SO won't work for me, maybe because it doesn't fit with this way of refreshing iframes, or with HTA, or I'm just too dumb with js to know how to make them work.
If anyone has a solution that I could just copy and use, even if I don't understand what I'm doing - it won't be very satisfying intellectually but at least I could focus on finishing my interface :) thanks a lot!
If you refresh the iframe by updating innerHTML from the text file, instead of doing a reload, it won't change the scroll position. Here's an example HTA:
<!DOCTYPE html>
<meta http-equiv="x-ua-compatible" content="ie=9">
<html>
<head>
<script>
function Refresh() {
var Iframe = document.getElementById("chatbox").contentWindow;
window.setInterval(function() {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile(".\\Chat.txt",1);
var FileContents = fh.AtEndOfStream ? "" : fh.ReadAll();
fh.Close();
Iframe.document.body.innerHTML = "<pre>" + FileContents + "</pre>"
}, 500);
}
</script>
<style>
#chatbox {height:30em;}
</style>
</head>
<body onload="Refresh()">
<iframe id=chatbox title="Chat Box">
</iframe>
</body>
</html>
I'm currently writing a little program that generates an html file and opens it with the default browser to start multiple downloads.
I don't want to open a tab/window for every download, so creating hidden iframes for the downloads seemed like a good solution.
I'm using onload on the iframes to find out if the download prompts for each download have shown up yet. This approach seems to be very unreliable in the Internet Explorer though.
So I'm wondering if there is there a way to fix this or maybe a better approach?
(Without libraries please.)
Here is my html/js code:
<!DOCTYPE html>
<!-- saved from url=(0016)http://localhost -->
<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Downloads</title>
<script>
"use strict";
var downloadsInfo = {
"http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe":"Status: Connecting",
"http://download.piriform.com/ccsetup410.exe":"Status: Connecting"
};
var i = 0;
var iv = setInterval(function() {
i = ++i % 4;
var j = 0;
var finished = true;
for (var key in downloadsInfo) {
var value = downloadsInfo[key];
if (value != "Status: Download Started!") {
value = value+Array(i+1).join(".");
finished = false;
}
document.getElementsByTagName("div")[j].innerHTML = key+"<br/>"+value;
j = j+1;
}
if (finished) {
alert('Done! You can close this window/tab now.');
clearInterval(iv);
}
}, 800);
</script>
</head><body>
<h3>Please wait for your downloads to start and do not reload this site.</h3>
<div></div> <br/><br/>
<div></div> <br/><br/>
<iframe src="http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe" onload="downloadsInfo['http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe'] = 'Status: Download Started!';" style="display:none"></iframe>
<iframe src="http://download.piriform.com/ccsetup410.exe" onload="downloadsInfo['http://download.piriform.com/ccsetup410.exe'] = 'Status: Download Started!';" style="display:none"></iframe>
</body></html>
Quite simply you can't know whether a native browser download started. Every browser has different ways this is handled, the user may set up his browser to prompt the location or he might just let it auto download to the Downloads folder (the default in most browsers nowadays). If he's prompting for a location he might cancel by mistake, yet your setup would still claim the download started. So, no, there is no way whatsoever to reliably inform the user that they can close a tab once all downloads are started/finished... provided that you use the native browser download mechanism.
The way to achieve this effect would be possibly by first downloading the file using Javascript (requiring you to have access to those files, hotlinking to third party files is of course not an option then). To see this in action try downloading a file from mega.nz. I was planning on writing up how to do this by hand, but there is already a nice (quite outdated) answer outlining this.
If the intention is only to ensure that the download has started you could implement a trigger on the back end to note when the file has been accessed. In it's simplest form this would look like:
Page download.html requests file.php?location=[...]&randomHash=1234
Once file.php is actually loaded it will set a flag in memory or the database that randomHash id 1234 has started.
file.php redirects the page with a 302 header to the actual file location.
download.html checks periodically using Ajax whether flag randomHash=1234 has been raised. If so it knows the download has started.
Indeed IE is reported to not always behave nicely with the onload event handler of iframes. There is an active bug tracker record opened.
The problem is discussed in a number of places around the web, and what seems to be the most reliable solution is to have an indirect download with nested iframes: the iframe loads a HTML file with an iframe that loads the file to download. The reason for that is that IE does not seem to like iframes that point to something else than HTML. So if you have the possibility to do that in your program:
For each file to download, generate a HTML file with a body that looks like this:
<iframe src="http://filetodownload.exe" style="display:none"></iframe>
Store this file in a temporary folder, e.g. C:\tmp\filetodownload.html
In your "master" generated HTML file, replace the iframe source with this intermediate file:
<iframe src="C:\tmp\filetodownload.html"
onload="downloadsInfo['http://filetodownload.exe']='Status: Download Started!';"
style="display:none"></iframe>
That may do the trick. But following IE's tradition, this could or could not work depending on the case...
If it does not work, some solutions that have proved useful include:
Put the onload handler in a function, and write in the definition of the iframe: onload="return theonloadfunction()" (even if the function does not return anything)
Instead of using the onload attribute, attach the event handler in javascript, like so:
iframe = document.getElementById("theiframeid")
iframe.attachEvent("onload", theonloadfunction);`
Note that attachEvent is for IE only. If you want to support other browsers you will have to detect it and use addEventListener for the non-IE cases.
Finally, you may try combinations of two or more of these solutions :)
<html>
<head>
<meta content = 'text/html;charset=utf-8' http-equiv = 'Content-Type'>
<meta content = 'utf-8' http-equiv = 'encoding'>
<script>
/*
First, I removed the setInterval(). Since you rely on the onload property we can aswell just check it on each onload.
Second, I changed your downloadsInfo to an object array.
Also be aware while testing, that some browsers cache your cancel/block choice and do not reask again for the same url.
Additionally firefox does not fire on frame downloads.
Furthermore the alert in your test might not show for overlapping or setting reasons.
*/
var downloadsInfo = [
{url: "http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe", Status: "Connecting"},
{url: "http://download.piriform.com/ccsetup410.exe", Status: "Connecting"}
];
//IE has a problem in sometimes merely firing the onload propery once, which we bypass by dynamically creating them
//It is also less limited.
function iframeConnect(){
for(var i=0, j=downloadsInfo.length; i<j; i++){
var tF = document.createElement('iframe');
tF.arrayIndex = i; //For convenience
tF.style.display = 'none';
//Normal load event, working in ie8-11, chrome, safari
tF.onload = function(){
iframeExecuted(this.arrayIndex);
};
//Workaround for firefox, opera and some ie9
tF.addEventListener('DOMSubtreeModified', function(){
iframeExecuted(this.arrayIndex);
}, false);
document.body.appendChild(tF);
tF.src = downloadsInfo[i].url;
}
}
function iframeExecuted(i){
downloadsInfo[i].Status = 'Executed';
var tStatus = iframeFinished();
var tE = document.querySelector('h3');
if (tStatus.Done) tE.innerHTML = 'Finished'
else tE.innerHTML = 'Processed ' + tStatus.Processed + ' of ' + tStatus.Started;
}
function iframeFinished(){
for(var i=0, j=downloadsInfo.length; i<j; i++){
if (downloadsInfo[i].Status != 'Executed') break;
}
//Note that the Processed value is not accurate, yet it solves is testing purpose.
return {Done: (i == j), Processed: i, Started: j}
}
</script>
</head>
<body onload = 'iframeConnect()'>
<h3>Please wait for your downloads to start and do not reload this site.</h3>
</body>
</html>
There is an HTML file with many embedded YouTube videos.Page load times were slow so I decided to use this JS file to force the page load an image instead of iframe, until the user clicks on it. http://www.skipser.com/p/2/p/youtube-video-embed-like-google-plus.html
CSS checks if the visitor uses mobile and optimizes the layout for mobile.I modified the above mentioned JS script to show smaller thumbnails so it will work better on mobile(no need to scroll horizontally).I have 2 version of that JS script now.
The goal: Check if visitor uses desktop.If yes, execute the regular gplus-youtubeembed.js.If visitor uses mobile then execute gplus-youtubeembed-mobile.js
This was the original HTML.It would only load the desktop version of JS.As a result, mobile visitors would see a very large video thumbnail.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width; initial-scale=1.0; user-scalable=yes">
<script src=gplus-youtubeembed.js></script>
<link rel=stylesheet type="text/css" href="css/style.css" media=screen />
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<script>optimizeYouTubeEmbeds()</script> <!--needed to load image instead of iframe-->
</body>
</html>
Then I used this method http://www.coalmarch.com/blog/how-to-execute-javascript-based-on-screen-size-using-jquery
if ( $(window).width() > 700) {
//added the content of gplus-youtubeembed.js here
}
else {
//added the content of gplus-youtubeembed-mobile.js here
}
I named that gplus-youtubeembed-combine.js and replaced gplus-youtubeembed.js with gplus-youtubeembed-combined.js , in the HTML doc.
The outcome: The only JS that gets executed is the mobile version.Desktop visitors see small thumbnails.Everyting works fine in mobile.Why doesn't the gplus-youtubeembed-combined.js work properly ? It's supposed to detect if the screen width is over 700 and execute the gplus-youtubeembed.js file but it doesn't.Any help is appreciated.Thanks !
From what I understand
if ( $(window).width() > 700) {
//added the content of gplus-youtubeembed.js here
}
else {
//added the content of gplus-youtubeembed-mobile.js here
}
works only when a window is first loaded or refreshed. Try changing the size of your window and refresh your page. If the code works, you'll need something to reload the script or the page on resize.
Something like this:
$(window).resize(function() {
// add the stuff here to execute the your slider again;
});
or this might do the trick:
<script>
function refresh() { location.reload(); }
</script>
<body onresize="refresh()">
I'm no expert but I had similar issue just a few minutes ago. Hope I helped.
Here is a little more detail on the second code that you asked for.
I'm only sharing with you what I'm learning as I go. I'm a real noob. Having the same problem as you but with a different snippet.
$(document).ready(function(){
$(window).on('resize', function(){
if ($(window).width() > 700) {
// code here
} esle {
// code here
}
});
});
But you said refreshing your page didn't make the JS run. Which means this method might not help you. Have you checked to make sure both JS run and work regardless of page width? Maybe test each JS individually to make sure the mobile version is good.
Sorry if I can't be much help to you. I'm learning as I try to solve my own issues. Thought yours was close to the issue I was having.
Problem was fixed.When I copy/pasted two JS files into the if/else statement, something broke the "if" statement so "else" was always being executed.I confirmed this by swapping the mobile and desktop versions and changing ">" to "<".In that case only desktop version would load.
Instead of copy/pasting the entire JS files into else/if, I left the common part out and added only the portion that was different in desktop/mobile version.Sounds simple, but it didn't come to my mind at the beginning.
The author of the original JS did not provide the mobile friendly version of the JS so people who use that code on their website might benefit from this post.One issue with the below code is that on mobile version, the image doesn't have a play button.It only has a thumbnail so make sure the visitor knows it's a video.This can be fixed by further tweaking the code but that's another topic.
Working version.
gplus-youtubeembedded-combine.js
// gplus-youtubeembed - Makes embedded YouTube video iframes Google+ style to improve page loading speed.
// Copyright (c) 2013 by Arun - http://www.skipser.com
// Licensed under the GNU LGPL license: http://www.gnu.org/copyleft/lesser.html
// For usage details, read - http://www.skipser.com/510
// Call this function at the end of the closing </body> tag.
function optimizeYouTubeEmbeds() {
// Get all iframes
var frames = document.getElementsByTagName( 'iframe' );
// Loop through each iframe in the page.
for ( var i = 0; i < frames.length; i++ ) {
// Find out youtube embed iframes.
if ( frames[ i ].src && frames[ i ].src.length > 0 && frames[ i ].src.match(/http(s)?:\/\/www\.youtube\.com/)) {
// For Youtube iframe, extract src and id.
var src=frames[i].src;
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
var id=(src.match(p) ? RegExp.$1 : false);
if(id == false) { continue;}
// Get width and height.
var w=frames[i].width;
var h=frames[i].height;
if(src == '' || w=='' || h=='') {continue;}
if ( $(window).width() > 700) {
// Thease are to position the play button centrally.
var pw=Math.ceil(w/2-38.5);
var ph=Math.ceil(h/2+38.5);
// The image+button overlay code.
var code='<div alt="For this Google+ like YouTube trick, please see http://www.skipser.com/510" style="width:'+w+'px; height:'+h+'px; margin:0 auto"><img src="http://i.ytimg.com/vi/'+id+'/hqdefault.jpg" style="width:'+w+'px; height:'+h+'px;" /><div style="background: url(\'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAE0AAABNCAYAAADjCemwAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABgtJREFUeNrtXE1IJEcUFuYgHhZZAzOQwKLsaeY4MuCisLNkMUYM+TtmQwgYQSEg8RCIBAMBSYIQPCgEEiEYISZIgrhzCRLYg+BBMiiDGCHGH4xGETH4O85M+huql7Knuqe7urq7ercePAZnuqtefXZVvfe911VToyRUUqdpVNMmTROaJjVt0bRN0/uapslnG/k+Sa5rIvfVPQ8gRTSNaRrX9B4Bxa3eI+3FSPvPjLxAnpAbA+7s7HxrcnLyk8XFxe82NjZ+Ozw8XDk9Pd29urr6r1Ao5EulUhGf+Bvf43dch+txH+5ngJgg/YVWXtI0RQ9qbGzso1wu99PJyclfJQGCdtAe2jWAlyL9h0ZeJGtQeQC9vb2Pstns1NnZ2X7JQ0H76Af9UeC1EHukldtksS4bPDw83Le5uTlfCkDQL/qnwEsS+6SSu/SThbWnJIHADsOTd1cGsG5p2qwbhUXayaCOj4//XFtbm52fn/96fHx8oK+v793W1tbXGhoaHkYikQf4xN/4Hr/jOlyP+5z0A7so4JqJ3YFITPenBgcHP8DuZmcA29vbT2ZnZ4fb29vfcONu4H60g/bs9Av7YCfl/8X8BuyObnwmk/kK7kGVRfqfhYWFb9wCZQUg2kc/VbArwl7q3jt+Adakd4rdysrC8/PzfzGlvADKTNEf+rWyC3ZT9zT5Btj6+nqmmmHRaPShn4Dpin6r/UNhvx/APZ2SVrsjFumRkZEPgwDLqLDDatPAOLycqjE7T5j22+Pa2toHMgCmK+yBXTafOGGbwy19l7R65LVt/VuZw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ixdLS0veyFL6IqhryrD5td3d3IaiSAz/q01QlJEclpKq55ay5VdXdHNXdEPUeAaeoN1Y4Rb0bxSHqLTxOUe97cop6s5hT1DvsboFTpyVwTlV1LofzzUGdAMPpjqizhtxEDjXqVCuuWFWdn8Yp6qQ+F6LOhHQh6vRRF6LOuRUg6kTl50n+B4KhcERZo7nRAAAAAElFTkSuQmCC\') no-repeat scroll 0 0 transparent;height: 77px;width: 77px; position:relative; margin-left:'+pw+'px; margin-top:-'+ph+'px;z-index:5;"></div></div>';
}
else {
var pw=Math.ceil(w/7.5-1.5);
var ph=Math.ceil(h/4.7+10);
var code='<div alt="For this Google+ like YouTube trick, please see http://www.skipser.com/510" style="max-width:100%;height:auto; margin:0 auto"><img src="http://i.ytimg.com/vi/'+id+'/hqdefault.jpg" style="max-width:100%;height:auto;" /> <div style="background: url(\'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAE0AAABNCAYAAADjCemwAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABgtJREFUeNrtXE1IJEcUFuYgHhZZAzOQwKLsaeY4MuCisLNkMUYM+TtmQwgYQSEg8RCIBAMBSYIQPCgEEiEYISZIgrhzCRLYg+BBMiiDGCHGH4xGETH4O85M+huql7Knuqe7urq7ercePAZnuqtefXZVvfe911VToyRUUqdpVNMmTROaJjVt0bRN0/uapslnG/k+Sa5rIvfVPQ8gRTSNaRrX9B4Bxa3eI+3FSPvPjLxAnpAbA+7s7HxrcnLyk8XFxe82NjZ+Ozw8XDk9Pd29urr6r1Ao5EulUhGf+Bvf43dch+txH+5ngJgg/YVWXtI0RQ9qbGzso1wu99PJyclfJQGCdtAe2jWAlyL9h0ZeJGtQeQC9vb2Pstns1NnZ2X7JQ0H76Af9UeC1EHukldtksS4bPDw83Le5uTlfCkDQL/qnwEsS+6SSu/SThbWnJIHADsOTd1cGsG5p2qwbhUXayaCOj4//XFtbm52fn/96fHx8oK+v793W1tbXGhoaHkYikQf4xN/4Hr/j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60hD4Dw0N9bix08mTFuo1DSFXJpP5UsQu6mRNC+XuSZjgX0QG9052z9D5aYYivXQQflpoIoKLi4tDsBFesb1OIgLpY09MxVwu97PXPJuT2FNqlgMMx8DAwPt+0ENOWA4p+TRMRT8TL075NKmYW3j1y8vLP8bj8Vf9pLudMrfS5Aj29/eXgsrE8+QIAs1GgeaZnp7+LKgUHm82KpC8J6ZiNpv9we+pKCrv6XuGHUUxPT09j2QoTeDNsPtWy6EZuDc1NfWp7CWldms5PK0a0qbixdLS0veyFL6IqhryrD5td3d3IaiSAz/q01QlJEclpKq55ay5VdXdHNXdEPUeAaeoN1Y4Rb0bxSHqLTxOUe97cop6s5hT1DvsboFTpyVwTlV1LofzzUGdAMPpjqizhtxEDjXqVCuuWFWdn8Yp6qQ+F6LOhHQh6vRRF6LOuRUg6kTl50n+B4KhcERZo7nRAAAAAElFTkSuQmCC\') no-repeat scroll 0 0 transparent;height: 77px;width: 77px; position:relative; margin-left:'+pw+'px; margin-top:-'+ph+'px;z-index:5;"></div><br><br><br></div>';
}
// Replace the iframe with a the image+button code.
var div = document.createElement('div');
div.innerHTML=code;
div=div.firstChild;
frames[i].parentNode.replaceChild(div, frames[i]);
i--;
}
}
}
// Replace preview image of a video with it's iframe.
function LoadYoutubeVidOnPreviewClick(id,w ,h) {
var code='<iframe src="https://www.youtube.com/embed/'+id+'/?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1" width="'+w+'" height="'+h+'" frameborder=0 allowfullscreen style="border:1px solid #ccc;" ></iframe>';
var iframe = document.createElement('div');
iframe.innerHTML=code;
iframe=iframe.firstChild;
var div=document.getElementById("skipser-youtubevid-"+id);
div.parentNode.replaceChild( iframe, div)
}
I've implemented the code here (it's my website) http://www.veryslowpc.com/security-measures.html
The outcome: in order to reduce page load times, embedded video iframes don't load until the user clicks on them, and the thumbnails are within page width when viewed on mobile.
Thank you for suggestions.
EDIT: The code should display the play button now.
I am trying to move a DOM node from the "root" page to a new pop-up that is created via window.open(). Here is the code I am using.
var win = window.open('/Search/Print', 'printSearchResults'),
table = $('#printTable');
win.document.close();
setTimeout(function () {
var el = win.document.createElement("table");
el.innerHTML = table.html();
win.document.body.appendChild(el);
}, 40);
It works in Chrome, but in IE8, I receive the following error: "Unknown runtime error."
I've also tried it this way:
var p = window.open('/Search/Print', 'printSearchResults'),
table = $('#printTable');
setTimeout(function () {
p.document.body.appendChild(table.clone(false)[0]);
}, 100);
Doing it this way, I receive "No such interface supported" in IE8. Again, Chrome works fine.
Does anyone have a way to do what I'm trying to achieve?
Here is the HTML for the pop-up window just for the sake of completeness:
<!DOCTYPE html>
<html>
<head>
<title>Print Results</title>
</head>
<body>
</body>
</html>
I tested your code on IE9 ( and IE8/7 browser mode).
Instead of el.innerHTML = table.html();
using jquery $(el).html(table.html()); fixed the issue.
To be able to use iframes and new windows, you should initialise them with addres: about:blank, before you write() to them. Also note that loading/opening the window/frame takes time, so you cannot write to them at right away. set a timeout, or check onload.
Please see this answer for more info.
Good luck!