set a Blob as the "src" of an iframe - javascript

The following code work perfectly in Chrome
<script>
function myFunction() {
var blob = new Blob(['<a id="a"><b id="b">hey!</b></a>'], {type : 'text/html'});
var newurl = window.URL.createObjectURL(blob);
document.getElementById("myFrame").src = newurl;
}
</script>
But it is not working with IE. Can some one please tell me what is wrong here.
The iframe "src" also set to the blob as shown below.
<iframe id="myFrame" src="blob:0827B944-D600-410D-8356-96E71F316FE4"></iframe>
Note:
I went on the window.navigator.msSaveOrOpenBlob(newBlob) path as well but no luck so far.

According to http://caniuse.com/#feat=datauri IE 11 has only got partial support for Data URI's. It states support is limited to images and linked resources like CSS or JS, not HTML files.
Non-base64-encoded SVG data URIs need to be uriencoded to work in IE and Firefox as according to this specification.

An example I did for Blob as a source of iFrame and working great with one important CAUTION / WARNING:
const blobContent = new Blob([getIFrameContent()], {type: "text/html"});
var iFrame = document.createElement("iframe");
iFrame.src = URL.createObjectURL(blobContent);
parent.appendChild(iFrame);
iFrame with Blob is not auto redirect protocol, meaning, having <script src="//domain.com/script.js"</script> inside the iframe head or body won't load the JS script at all even on Chrome 61 (current version).
it doesn't know what to do with source "blob" as protocol. this is a BIG warning here.
Solution: This code will solve the issue, it runs mostly for VPAID ads and working for auto-protocol:
function createIFrame(iframeContent) {
let iFrame = document.createElement("iframe");
iFrame.src = "about:blank";
iFrameContainer.innerHTML = ""; // (optional) Totally Clear it if needed
iFrameContainer.appendChild(iFrame);
let iFrameDoc = iFrame.contentWindow && iFrame.contentWindow.document;
if (!iFrameDoc) {
console.log("iFrame security.");
return;
}
iFrameDoc.write(iframeContent);
iFrameDoc.close();
}

I've run into the same problem with IE. However, I've been able to get the download/save as piece working in IE 10+ using filesaver.js.
function onClick(e) {
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"});
saveAs(blob, fileName);
e.preventDefault();
return false;
};
$('#download').click(onClick);
See http://jsfiddle.net/o0wk71n2/ (based on answer by #kol to JavaScript blob filename without link)

Related

Show blue dot in chrome tab [duplicate]

I have a web application that's branded according to the user that's currently logged in. I'd like to change the favicon of the page to be the logo of the private label, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?
I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?
Why not?
var link = document.querySelector("link[rel~='icon']");
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';
Here’s some code that works in Firefox, Opera, and Chrome (unlike every other answer posted here). Here is a different demo of code that works in IE11 too. The following example might not work in Safari or Internet Explorer.
/*!
* Dynamically changing favicons with JavaScript
* Works in all A-grade browsers except Safari and Internet Explorer
* Demo: http://mathiasbynens.be/demo/dynamic-favicons
*/
// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];
function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}
You would then use it as follows:
var btn = document.getElementsByTagName('button')[0];
btn.onclick = function() {
changeFavicon('http://www.google.com/favicon.ico');
};
Fork away or view a demo.
If you have the following HTML snippet:
<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />
You can change the favicon using Javascript by changing the HREF element on this link, for instance (assuming you're using JQuery):
$("#favicon").attr("href","favicon2.png");
You can also create a Canvas element and set the HREF as a ToDataURL() of the canvas, much like the Favicon Defender does.
jQuery Version:
$("link[rel='shortcut icon']").attr("href", "favicon.ico");
or even better:
$("link[rel*='icon']").attr("href", "favicon.ico");
Vanilla JS version:
document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";
document.querySelector("link[rel*='icon']").href = "favicon.ico";
A more modern approach:
const changeFavicon = link => {
let $favicon = document.querySelector('link[rel="icon"]')
// If a <link rel="icon"> element already exists,
// change its href to the given link.
if ($favicon !== null) {
$favicon.href = link
// Otherwise, create a new element and append it to <head>.
} else {
$favicon = document.createElement("link")
$favicon.rel = "icon"
$favicon.href = link
document.head.appendChild($favicon)
}
}
You can then use it like this:
changeFavicon("http://www.stackoverflow.com/favicon.ico")
Here's a snippet to make the favicon be an emoji, or text. It works in the console when I'm at stackoverflow.
function changeFavicon(text) {
const canvas = document.createElement('canvas');
canvas.height = 64;
canvas.width = 64;
const ctx = canvas.getContext('2d');
ctx.font = '64px serif';
ctx.fillText(text, 0, 64);
const link = document.createElement('link');
const oldLinks = document.querySelectorAll('link[rel="shortcut icon"]');
oldLinks.forEach(e => e.parentNode.removeChild(e));
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = canvas.toDataURL();
document.head.appendChild(link);
}
changeFavicon('❤️');
The favicon is declared in the head tag with something like:
<link rel="shortcut icon" type="image/ico" href="favicon.ico">
You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag.
Here's some code I use to add dynamic favicon support to Opera, Firefox and Chrome. I couldn't get IE or Safari working though. Basically Chrome allows dynamic favicons, but it only updates them when the page's location (or an iframe etc in it) changes as far as I can tell:
var IE = navigator.userAgent.indexOf("MSIE")!=-1
var favicon = {
change: function(iconURL) {
if (arguments.length == 2) {
document.title = optionalDocTitle}
this.addLink(iconURL, "icon")
this.addLink(iconURL, "shortcut icon")
// Google Chrome HACK - whenever an IFrame changes location
// (even to about:blank), it updates the favicon for some reason
// It doesn't work on Safari at all though :-(
if (!IE) { // Disable the IE "click" sound
if (!window.__IFrame) {
__IFrame = document.createElement('iframe')
var s = __IFrame.style
s.height = s.width = s.left = s.top = s.border = 0
s.position = 'absolute'
s.visibility = 'hidden'
document.body.appendChild(__IFrame)}
__IFrame.src = 'about:blank'}},
addLink: function(iconURL, relValue) {
var link = document.createElement("link")
link.type = "image/x-icon"
link.rel = relValue
link.href = iconURL
this.removeLinkIfExists(relValue)
this.docHead.appendChild(link)},
removeLinkIfExists: function(relValue) {
var links = this.docHead.getElementsByTagName("link");
for (var i=0; i<links.length; i++) {
var link = links[i]
if (link.type == "image/x-icon" && link.rel == relValue) {
this.docHead.removeChild(link)
return}}}, // Assuming only one match at most.
docHead: document.getElementsByTagName("head")[0]}
To change favicons, just go favicon.change("ICON URL") using the above.
(credits to http://softwareas.com/dynamic-favicons for the code I based this on.)
Or if you want an emoticon :)
var canvas = document.createElement("canvas");
canvas.height = 64;
canvas.width = 64;
var ctx = canvas.getContext("2d");
ctx.font = "64px serif";
ctx.fillText("☠️", 0, 64);
$("link[rel*='icon']").prop("href", canvas.toDataURL());
Props to https://koddsson.com/posts/emoji-favicon/
in most cases, favicon is declared like this.
<link rel="icon" href"...." />
This way you can attain reference to it with this.
const linkElement = document.querySelector('link[rel=icon]');
and you can change the picture with this
linkElement.href = 'url/to/any/picture/remote/or/relative';
The only way to make this work for IE is to set you web server to treat requests for *.ico to call your server side scripting language (PHP, .NET, etc). Also setup *.ico to redirect to a single script and have this script deliver the correct favicon file. I'm sure there is still going to be some interesting issues with cache if you want to be able to bounce back and forth in the same browser between different favicons.
I would use Greg's approach and make a custom handler for favicon.ico
Here is a (simplified) handler that works:
using System;
using System.IO;
using System.Web;
namespace FaviconOverrider
{
public class IcoHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/x-icon";
byte[] imageData = imageToByteArray(context.Server.MapPath("/ear.ico"));
context.Response.BinaryWrite(imageData);
}
public bool IsReusable
{
get { return true; }
}
public byte[] imageToByteArray(string imagePath)
{
byte[] imageByteArray;
using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
{
imageByteArray = new byte[fs.Length];
fs.Read(imageByteArray, 0, imageByteArray.Length);
}
return imageByteArray;
}
}
}
Then you can use that handler in the httpHandlers section of the web config in IIS6 or use the 'Handler Mappings' feature in IIS7.
There is a single line solution for those who use jQuery:
$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');
I use this feature all the time when developing sites ... so I can see at-a-glance which tab has local, dev or prod running in it.
Now that Chrome supports SVG favicons it makes it a whole lot easier.
Tampermonkey Script
Have a gander at https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f for a tampermonkey script that points to a demo site I chucked up at https://elliz.github.io/svg-favicon/
Basic code
Adapted this from another answer ... could be improved but good enough for my needs.
(function() {
'use strict';
// play with https://codepen.io/elliz/full/ygvgay for getting it right
// viewBox is required but does not need to be 16x16
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
<circle cx="8" cy="8" r="7.2" fill="gold" stroke="#000" stroke-width="1" />
<circle cx="8" cy="8" r="3.1" fill="#fff" stroke="#000" stroke-width="1" />
</svg>
`;
var favicon_link_html = document.createElement('link');
favicon_link_html.rel = 'icon';
favicon_link_html.href = svgToDataUri(svg);
favicon_link_html.type = 'image/svg+xml';
try {
let favicons = document.querySelectorAll('link[rel~="icon"]');
favicons.forEach(function(favicon) {
favicon.parentNode.removeChild(favicon);
});
const head = document.getElementsByTagName('head')[0];
head.insertBefore( favicon_link_html, head.firstChild );
}
catch(e) { }
// functions -------------------------------
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function svgToDataUri(svg) {
// these may not all be needed - used to be for uri-encoded svg in old browsers
var encoded = svg.replace(/\s+/g, " ")
encoded = replaceAll(encoded, "%", "%25");
encoded = replaceAll(encoded, "> <", "><"); // normalise spaces elements
encoded = replaceAll(encoded, "; }", ";}"); // normalise spaces css
encoded = replaceAll(encoded, "<", "%3c");
encoded = replaceAll(encoded, ">", "%3e");
encoded = replaceAll(encoded, "\"", "'"); // normalise quotes ... possible issues with quotes in <text>
encoded = replaceAll(encoded, "#", "%23"); // needed for ie and firefox
encoded = replaceAll(encoded, "{", "%7b");
encoded = replaceAll(encoded, "}", "%7d");
encoded = replaceAll(encoded, "|", "%7c");
encoded = replaceAll(encoded, "^", "%5e");
encoded = replaceAll(encoded, "`", "%60");
encoded = replaceAll(encoded, "#", "%40");
var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim();
return dataUri;
}
})();
Just pop your own SVG (maybe cleaned with Jake Archibald's SVGOMG if you're using a tool) into the const at the top. Make sure it is square (using the viewBox attribute) and you're good to go.
I use favico.js in my projects.
It allows to change the favicon to a range of predefined shapes and also custom ones.
Internally it uses canvas for rendering and base64 data URL for icon encoding.
The library also has nice features: icon badges and animations; purportedly, you can even stream the webcam video into the icon :)
According to WikiPedia, you can specify which favicon file to load using the link tag in the head section, with a parameter of rel="icon".
For example:
<link rel="icon" type="image/png" href="/path/image.png">
I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.
You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.
Yes totally possible
Use a querystring after the favicon.ico (and other files links -
see answer link below)
Simply make sure the server responds to the "someUserId" with
the correct image file (that could be static routing rules, or
dynamic server side code).
e.g.
<link rel="shortcut icon" href="/favicon.ico?userId=someUserId">
Then whatever server side language / framework you use should easily be able to find the file based on the userId and serve it up in response to that request.
But to do favicons properly (its actually a really complex subject) please see the answer here https://stackoverflow.com/a/45301651/661584
A lot lot easier than working out all the details yourself.
Enjoy.
Testing the proposed solutions on 2021 on Chrome, I found that some times the browser cache the favicon and do not show the change, even if the link was changed
This code worked (similar to previous proposal but adds a random parameter to avoid caching)
let oldFavicon = document.getElementById('favicon')
var link = document.createElement('link')
link.id = 'favicon';
link.type = 'image/x-icon'
link.rel = 'icon';
link.href = new_favicon_url +'?=' + Math.random();
if (oldFavicon) {
document.head.removeChild(oldFavicon);
}
document.head.appendChild(link);
Copied from https://gist.github.com/mathiasbynens/428626#gistcomment-1809869
in case that someone else have the same problem

Javascript download file works only on chrome browser

I am using this function, to download a text file.
This code works only on chrome browser,
What is eqivelent code in other browser for
IE
Firfox
Safari
Kindly guide me
function downloadFileFnc(text, fileName)
{
var textCode = new Blob([text], { type: "application/text" });
var dldLnkVar = document.createElement('a');
dldLnkVar.href = window.URL.createObjectURL(textCode);
dldLnkVar.setAttribute('download', fileName);
dldLnkVar.click();
}

Angularjs/Restangular, how to name file blob for download?

For some reason this seems easier in IE than Chrome/FF:
$scope.download = function() {
Restangular.one(myAPI)
.withHttpConfig({responseType: 'blob'}).customGET().then(function(response) {
//IE10 opens save/open dialog with filename.zip
window.navigator.msSaveOrOpenBlob(response, 'filename.zip');
//Chrome/FF downloads a file with random name
var url = (window.URL || window.webkitURL).createObjectURL(response);
window.location.href = url;
});
};
Is there a way to do something similar to how IE10+ works? That is, I can specify a file name/type (will only be zip)?
As soon as you have your object url you can create an anchor and set the download attribute to the filename you want, set the href to the object url, and then just call click
var myBlob = new Blob(["example"],{type:'text/html'})
var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();
Download attribute compatibility
Just use https://www.npmjs.com/package/angular-file-saver
Browser Support table can be seen here: https://github.com/eligrey/FileSaver.js/

How to open generated pdf using jspdf in new window

I am using jspdf to generate a pdf file. Every thing is working fine. But how to open generated
pdf in new tab or new window.
I am using
doc.output('datauri');
Which is opening the pdf in same tab.
Based on the source you can use the 'dataurlnewwindow' parameter for output():
doc.output('dataurlnewwindow');
Source in github:
https://github.com/MrRio/jsPDF/blob/master/jspdf.js#L914
All possible cases:
doc.output('save', 'filename.pdf'); //Try to save PDF as a file (not works on ie before 10, and some mobile devices)
doc.output('datauristring'); //returns the data uri string
doc.output('datauri'); //opens the data uri in current window
doc.output('dataurlnewwindow'); //opens the data uri in new window
This solution working for me
window.open(doc.output('bloburl'))
I have to use this to load the PDF directly. Using doc.output('dataurlnewwindow'); produces an ugly iframe for me. Mac/Chrome.
var string = doc.output('datauristring');
var x = window.open();
x.document.open();
x.document.location=string;
this code will help you to open generated pdf in new tab with required title
let pdf = new jsPDF();
pdf.setProperties({
title: "Report"
});
pdf.output('dataurlnewwindow');
Or...
You can use Blob to achive this.
Like:
pdf.addHTML($('#content'), y, x, options, function () {
var blob = pdf.output("blob");
window.open(URL.createObjectURL(blob));
});
That code let you create a Blob object inside the browser and show it in the new tab.
Search in jspdf.js this:
if(type == 'datauri') {
document.location.href ='data:application/pdf;base64,' + Base64.encode(buffer);
}
Add :
if(type == 'datauriNew') {
window.open('data:application/pdf;base64,' + Base64.encode(buffer));
}
call this option 'datauriNew' Saludos ;)
using javascript you can send the generated pdf to a new window using the following code.
var string = doc.output('datauristring');
var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"
var x = window.open();
x.document.open();
x.document.write(iframe);
x.document.close();
This is how I handle it.
window.open(doc.output('bloburl'), '_blank');
Generally you can download it, show, or get a blob string:
const pdfActions = {
save: () => doc.save(filename),
getBlob: () => {
const blob = doc.output('datauristring');
console.log(blob)
return blob
},
show: () => doc.output('dataurlnewwindow')
}
STEP 1
Turn off addblock
STEP 2
Add
window.open(doc.output('bloburl'), '_blank');
Or try
doc.output('dataurlnewwindow')
Javascript code
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(doc.output("blob"), "Name.pdf");
} else {
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
doc.autoPrint();
window.open(
URL.createObjectURL(doc.output("blob")),
"_blank",
"height=650,width=500,scrollbars=yes,location=yes"
);
// For Firefox it is necessary to delay revoking the ObjectURL
setTimeout(() => {
window.URL.revokeObjectURL(doc.output("bloburl"));
}, 100);
}
This works for me!!!
When you specify window features, it will open in a new window
Just like :
window.open(url,"_blank","top=100,left=200,width=1000,height=500");
Step I: include the file and plugin
../jspdf.plugin.addimage.js
Step II: build PDF content
var doc = new jsPDF();
doc.setFontSize(12);
doc.text(35, 25, "Welcome to JsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 386, 386);
Step III: display image in new window
doc.output('dataurlnewwindow');
Stepv IV: save data
var output = doc.output();
return btoa( output);
Javascript code: Add in end line
$("#pdf_preview").attr("src", pdf.output('datauristring'));
HTML Code: Insert in body
<head>
</head>
<body>
<H1>Testing</h1>
<iframe id="pdf_preview" type="application/pdf" src="" width="800" height="400"></iframe>
</body>
</html>
preview within same window inside iframe along with with other contents.
Additionally, it is important to remember that the output method has other values and it might be interesting to test all of them to choose the ideal one for your case.
https://artskydj.github.io/jsPDF/docs/jsPDF.html#output
test one line at a time:
doc.output('arraybuffer');
doc.output('blob');
doc.output('bloburi');
doc.output('bloburl');
doc.output('datauristring');
doc.output('dataurlstring');
doc.output('datauri');
doc.output('dataurl');
doc.output('dataurlnewwindow');
doc.output('pdfobjectnewwindow');
doc.output('pdfjsnewwindow');

How to get WHOLE content of iframe?

I need to get whole content of iframe from the same domain. Whole content means that I want everything starting from <html> (including), not only <body> content.
Content is modified after load, so I can't get it once again from server.
I belive I've found the best solution:
var document = iframeObject.contentDocument;
var serializer = new XMLSerializer();
var content = serializer.serializeToString(document);
In content we have full iframe content, including DOCTYPE element, which was missing in previous solutions. And in addition this code is very short and clean.
If it is on the same domain, you can just use
iframe.contentWindow.document.documentElement.innerHTML
to get the content of the iframe, except for the <html> and </html> tag, where
iframe = document.getElementById('iframeid');
$('input.test').click(function(){
$('textarea.test').text($('iframe.test').contents());
});
You can get the literal source of any file on the same domain with Ajax, which does not render the html first-
//
function fetchSource(url, callback){
try{
var O= new XMLHttpRequest;
O.open("GET", url, true);
O.onreadystatechange= function(){
if(O.readyState== 4 && O.status== 200){
callback(O.responseText);
}
};
O.send(null);
}
catch(er){}
return url;
}
function printSourceCode(text){
var el= document.createElement('textarea');
el.cols= '80';
el.rows= '20';
el.value= text;
document.body.appendChild(el);
el.focus();
}
fetchSource(location.href, printSourceCode);

Categories

Resources