HTML redirect without opening new tab - html

I have the following code which redirects to a random webpage although it does so by opening a new tab which is often blocked by web browsers. Can this be amended to open the new site in the same tab?
Thanks in advance
<script>
var links = [ "google.com",
"youtube.com",
"reddit.com",
"apple.com"]
var time = 3000;
var openSite = function() {
var randIdx = Math.random() * links.length;
randIdx = parseInt(randIdx, 10);
var link = 'https://www.' + links[randIdx];
return link;
};
setTimeout(function(){
open(openSite())
}, time);
</script>
enter image description here

Maybe something like:
window.location.href = openSite();

Related

JsPDF - Not allowed to navigate top frame to data URL

After updating Google Chrome, the report jsPDF in a new Window does not work any more.
The console shows the message:
Not allowed to navigate top frame to data URL:
data:application/pdf;base64,JVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1....
Can you help-me?
Thanks.
This works well now that chrome has removed top frame navigation. Only downloading the pdf in chrome gives problem. Download works in well in firefox tho.
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();
Apparently Google Chrome has removed support for top-frame navigation, you can see more informations here: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/GbVcuwg_QjM
You may try to render the jsPDF to an iFrame
I recently had the same problem using FileReader object to read content and show my JSReport.
var reader = new FileReader();
reader.onload = function (e) {
window.open(reader.result, "_blank");
}
reader.readAsDataURL(blob);
Unfortunatly after chrome update all my report stopped working.
I tried to fix this by using Blob object and it's still working but if you have a popup blocker it will not work.
var file = new Blob([blob], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
I finally find a way to avoid this problem by creating the iFrame dynamically after reading this topic and i decided to share the solution.
var file = new Blob([blob], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
var win = window.open();
win.document.write('<iframe src="' + fileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>')
Maybe can help, create a function to export with the download attribute html5:
var docPdf = doc.output();
exportToFile(docPdf,defaults.type);
function exportToFile(data,type){
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/'+type+';filename='+'exportar.'+type+';'+'charset=utf-8,' + encodeURI(data);
hiddenElement.target = '_blank';
hiddenElement.download = 'exportar.'+type;
hiddenElement.click();
}
the download property of the a element has to contain a file name.
function window_download( datauri )
{
const match = datauri.match(/(filename=)([^;]+)/);
const fileName = match ? match[2] : '' ;
if ( fileName )
{
const downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.innerHTML = "Download File";
downloadLink.href = datauri ;
downloadLink.click();
}
else
{
throw 'missing download file name' ;
}
// get contents of pdf from jsPDF as a data uri.
const uri = pdf.output('datauristring', 'packing-list.pdf' );
window_download( uri ) ;
<iframe id="ManualFrame"
frameborder="0"
style="border:0"
allowfullscreen>
</iframe>
<script>
$(function () {
setManualFrame();
});
function setManualFrame() {
$("#ManualFrame").attr("height", screen.height);
$("#ManualFrame").attr("width", screen.width);
$("#ManualFrame").attr("src", "data:application/pdf;base64," + Your_PDF_Data);
}
</script>
var pdfUrl = doc.output('datauri').substring(doc.output('datauri').indexOf(',')+1);
var binary = atob(pdfUrl.replace(/\s/g, ''));
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
var blob = new Blob( [view], { type: "application/pdf" });
var url = URL.createObjectURL(blob);
function openPDF(){
window.open(url);
}
As chrome removed its support for - Top-frame navigation. Luckily jsPDF has an API - "save()", which offers the same functionality as doc.output('datauri')
Below is the example implementation of save()
var doc = new jsPDF();
doc.addImage(imgData, 'JPEG', 0, 0, 300, 160);
doc.save('fileName.pdf');
save(filename, options) → {jsPDF|Promise}
Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf'). Uses FileSaver.js-method saveAs.
Refer JSPDF documentation for more information -
Add attrbute download
Based on Joyston's answer, but without reparsing and therefore without additional need to escape something:
x=window.open();
iframe=x.document.createElement('iframe')
iframe.width='100%'
iframe.height='100%'
iframe.frameBorder=0
iframe.style="border: 0"
iframe.src='data:text/html........' //data-uri content here
x.document.body.appendChild(iframe);
Not related to jspdf, but did help me here (and this question is the top hit at google): If specifying a download="..." attribute to the anchor tag, the download prompt will properly open up.
#kuldeep-choudhary
Hi, in fact, to solve i'm using object tag with angularJS 1.5.xx
<object ng-attr-data="{{data}}" type="application/pdf"></object>
and in script:
$scope.doc.data = $sce.trustAsResourceUrl(doc.output("datauristring"));
In pure javascript, maybe like this works:
html:
<object id="obj" type="application/pdf" ></object>
js:
document.elementById('obj').data = doc.output("datauristring");
please, try and correct-me if I wrong.
Using download="" made me able to download the file
/**
* Creates an anchor element `<a></a>` with
* the base64 pdf source and a filename with the
* HTML5 `download` attribute then clicks on it.
* #param {string} pdf
* #return {void}
*/
function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "vct_illustration.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
Source from: https://medium.com/octopus-labs-london/downloading-a-base-64-pdf-from-an-api-request-in-javascript-6b4c603515eb
In angular2+ -
app.component.html -
<object id="obj" [attr.data] type="application/pdf"> </object>
app.component.ts
document.getElementById('obj').dataset.data = doc.output("datauristring");
var blob = doc.output("blob");
window.open(URL.createObjectURL(blob));

Error in Apple's TVML documentation? pushPage function doesn't work

UPDATED 6/1/17 with the correct code pasted at the bottom.
I'm working through Apple's TVML guide, section 2: Navigating Between Pages. (https://developer.apple.com/library/content/documentation/TVMLKitJS/Conceptual/TVMLProgrammingGuide/NavigatingBetweenPages.html#//apple_ref/doc/uid/TP40016718-CH9-SW1)
Everything is fine until the last bit (Listing 4-4), which allow you to use the menu button on the remote to return to the previous page. Whenever I try it, my sample app simply won't load:
var baseURL;
function loadingTemplate() {
var template = '<document><loadingTemplate><activityIndicator><text>Loading</text></activityIndicator></loadingTemplate></document>';
var templateParser = new DOMParser();
var parsedTemplate = templateParser.parseFromString(template, "application/xml");
return parsedTemplate;
}
function getDocument(extension) {
var templateXHR = new XMLHttpRequest();
var url = baseURL + extension;
var loadingScreen = loadingTemplate();
templateXHR.responseType = "document";
templateXHR.addEventListener("load", function() {pushPage(templateXHR.responseXML, loadingScreen);}, false);
templateXHR.open("GET", url, true);
templateXHR.send();
}
function pushPage(page, loading) {
var currentDoc = getActiveDocument();
navigationDocument.replaceDocument(page, loading);
}
App.onLaunch = function(options) {
baseURL = options.BASEURL;
var extension = "templates/InitialPage.xml";
getDocument(extension);
}
What am I missing?
This works:
var baseURL;
function loadingTemplate() {
var template = '<document><loadingTemplate><activityIndicator><text>Loading</text></activityIndicator></loadingTemplate></document>';
var templateParser = new DOMParser();
var parsedTemplate = templateParser.parseFromString(template, "application/xml");
navigationDocument.pushDocument(parsedTemplate);
return parsedTemplate;
}
function getDocument(extension) {
var templateXHR = new XMLHttpRequest();
var url = baseURL + extension;
var loadingScreen = loadingTemplate();
templateXHR.responseType = "document";
templateXHR.addEventListener("load", function() {pushPage(templateXHR.responseXML, loadingScreen);}, false);
templateXHR.open("GET", url, true);
templateXHR.send();
}
function pushPage(page, loading) {
navigationDocument.replaceDocument(page, loading);
}
App.onLaunch = function(options) {
baseURL = options.BASEURL;
var extension = "templates/InitialPage.xml";
getDocument(extension);
}
Yes, I believe there is a mistake. They should have kept the line
navigationDocument.pushDocument(parsedTemplate);
at the end of the loadingTemplate method.
The idea is to push the loading page, then replace it with the new page.
On a side note, the line
var currentDoc = getActiveDocument();
has no business here. This code was obviously not tested or reviewed.

Download link for video file

I have a video for which I want to provide a download link. However, having created a simple Download tag, when I click on it (in Firefox & Chrome) it starts playing the video instead of allowing the video to be downloaded. Is there a way that works in all current browsers to force them to offer the save-as dialog?
Try using the download attribute.
<a href="myvideo.mp4" download>Download</a>
More at:
http://www.w3schools.com/tags/att_a_download.asp
you should also try this.
if (isVideo) {
var div = document.createElement('div');
div.className = "column";
var vid = document.createElement('video');
var source = document.createElement('source');
source.type = "video/mp4";
source.src = display_src;
vid.appendChild(source);
vid.poster;
vid.controls = true;
var alink = document.createElement('a');
alink.href = display_src;
alink.id = 'downlo_click';
}
alink.text = "Repost"
// window.open(alink, '_self');
div.appendChild(vid);
div.appendChild(alink);
document.getElementById('gamediv').appendChild(div)
document.getElementById('downlo_click').addEventListener('click', function() {
var x = new XMLHttpRequest();
x.open("GET", display_src, true);
x.responseType = 'blob';
x.onload = function(e) {
download(x.response, "abcd.mp4", "video/mp4");
}
x.send();
// window.open(alink, '_self');
// download("data:text/html,"display_src, display_src);
});
}

Display a new html/web page in panel

I am developing an addon for firefox using addon-SDK method. I would like to know if there is anyway to change the html(contentURL) displayed in that panel to a new webpage upon clicking a link in that contentURL. Thanks in advance.
Vignesh here's code that receives the url clicked on:
https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/panel#Scripting_panel_content
var myScript = "window.addEventListener('click', function(event) {" +
" var t = event.target;" +
" if (t.nodeName == 'A')" +
" self.port.emit('click-link', t.toString());" +
"}, false);"
var panel = require("sdk/panel").Panel({
contentURL: "http://www.bbc.co.uk/mobile/index.html",
contentScript: myScript
});
panel.port.on("click-link", function(url) {
console.log(url);
});
panel.show();
So then you can change that to be instead of console.log(url) you can make it find your panel and changes its iframes location to that url. Im not sure how to do this with sdk methods, maybe someone else can share. I would try to do this though:
panel.port.on("click-link", function(url) {
panel.contentURL = url;
});
edit:
panel.contentURL = url may not work so you have to do it like this:
const { getMostRecentBrowserWindow } = require('sdk/window/utils');
var aXULBrowser = getMostRecentBrowserWindow();
aXULBrowser.getElementById('ID OF YOUR PANEL, probably same as id to your widget here').getElementsByTagName('iframe').contentWindow.location = url;

How to include a link in the HTML5 notification?

I would like to be able to set a link/permalink to each notification, so when user clicks on it; then he is taken to the permalink location,
I've seen this answer which has a solution that's a little bit different because static link is used,
I would like to, somehow:
var noti = window.webkitNotifications.createNotification(
'http://funcook.com/img/favicon.png',
'HTML5 Notification',
'HTML5 Notification content...',
'http://mycustom.dynamic.link.com/' /* invented code */
)
noti.onclose = function(){ alert(':(') };
noti.onclick = function(){
window.location.href = $(this).url; /* invented code */
};
noti.show();
Any chance? (I really don't like the static html file solution... I would like to keep this syntax)
How about something like this?
var createNotificationWithLink = function(image, title, content, link) {
var notification = window.webkitNotifications.createNotification(image, title, content);
notification.onclose = function() {
alert(':(');
};
notification.onclick = function() {
window.location.href = link;
};
return notification;
};
Now you can call createNotificationWithLink whenever you want to create a notification:
var noti = createNotificationWithLink(
'http://funcook.com/img/favicon.png',
'HTML5 Notification',
'HTML5 Notification content...',
'http://mycustom.dynamic.link.com/'
);
noti.show();
You can also move noti.show(); into the createNotificationWithLink function if you like (notification.show();). I don't know if you want the notification to be shown automatically when you create it...
You can pass a data property that you can read from within the onclick event handler as e.target.data.
var notification = new window.Notification("Hello!",
{
body: "Hello world!",
data: "https://www.example.com/?id=" + 123
});
notification.onclick = function(e) {
window.location.href = e.target.data;
}
noti.onclick = function() {
window.open("http://www.stackoverflow.com")
};
More on how to use window.open: http://www.w3schools.com/jsref/met_win_open.asp4
HTML5 Notification Resource: http://www.html5rocks.com/en/tutorials/notifications/quick/ (If this doesn't answer you're question)
For Each one you could have:
var noti1 = window.webkitNotifications.createNotification(
'http://funcook.com/img/favicon.png',
'HTML5 Notification',
'HTML5 Notification content...',
var noti2 = window.webkitNotifications.createNotification(
'http://funcook.com/img/favicon.png',
'HTML5 Notification #2',
'HTML5 Notification #2 content...',
etc
and then
noti1.onclick = function() {
window.open("http://www.stackoverflow.com")
};
noti2.onclick = function() {
window.open("http://www.example.com")
};
hope that helps :)
You can add the url as a property to 'noti', then call that property with this.yourpropertyname
example:
noti.myurl = 'http://stackoverflow.com';
...
noti.onclick = function(){
window.location.href = this.myurl;
};
hope this helps.
For anyone, who needs to open a new browser window(tab), but does not want the parent window(tab) to be replaced and focused upon notification click, this code snippet will do the trick:
var notification = new window.Notification("Hello!", {
body: "Hello world!",
data: "https://www.google.com/"
});
notification.onclick = function(event) {
event.preventDefault(); //prevent the browser from focusing the Notification's tab, while it stays also open
var new_window = window.open('','_blank'); //open empty window(tab)
new_window.location = event.target.data; //set url of newly created window(tab) and focus
};