How do I link to a pdf in AngularJS? - javascript

The code below contains a hyperlink that causes a spring-generated pdf from the server to be loaded in a new browser window when a user clicks on the link. The problem is that some users have pop-ups blocked in their browsers. What specific changes need to be made to the code below in order for the pdf to open IN THE SAME BROWSER WINDOW when a user clicks on the link? Note that this pdf is generated by a spring controller.
Here is the html:
<p><a ng-click="getPdf()">Show PDF</a></p>
And here is the Angular controller code:
angular.module('message', ['auth']).controller('message', function($scope, $http, $sce, auth) {
$scope.authenticated = function() {
return auth.authenticated;
}
$scope.getPdf = function(){
$http.get('/api/some-pdfr', {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
}
});

window.open supports a second parameter, windowName. You can set this to "_self" to open the URL in the same window.
window.open(fileURL, "_self");
See here for more information.
A better way might be to make the directive update the links href to the correct url before it navigates. That would let you use _blank as the target and open it in a new tab/window.

Instead of calling window.open, you need to provide the user with a link to click on whose href is fileUrl. You can either do this by generating the PDF before the user clicks on the link, or by providing them with a separate link after the PDF has been generated.

Related

angularjs: main page's UI blocked while loading second page which is opened into new tab

Idea is to add ctrl + click functionality to table row <tr>. When user clicks on table row while holding ctrl button it opens details page in new tab.
This is table row's template:
<tr class="clickable-row" ng-repeat="row in books track by row.id" ng-click="testCtrl.navigate($event, row.id)">
This is ng-click function:
function navigate($event, rowId) {
const url = `/books/${rowId}`;
// on ctrl||cmd + click open details in new tab
if ($event.ctrlKey || $event.metaKey) {
$window.open(url, '_blank');
return;
}
$location.path(url);
}
Problem: when I open details view into new tab it's blocking main page's UI while details view is loading into new tab.
Just created small test fiddle with plain JavaScript and it's working fine, when you click "Open new tab" button while holding ctrl key, it's opening a new tab with same page and in the same time you can click again on this button and it's not blocked.
Here is the js-fiddle
How I understand it, there could be problem into AngularJS and same domain loading into new tab. Tested this same case with $window.open('https://www.google.lv/', '_blank'); and in this time it's not blocking main pages UI.
What is the solution?
Problem was because both tabs were running with same process and that cause UI blocking.
Found a solution for this.
Adding a rel="noopener" attribute prevents the new page from being able to access the window.opener property and will ensure it runs in a separate process.
function navigate($event, rowId) {
const url = `/books/${rowId}`;
// on ctrl||cmd + click open details in new tab
if ($event.ctrlKey || $event.metaKey) {
const link = $document[0].createElement('a');
$document[0].body.appendChild(link);
link.setAttribute('type', 'hidden');
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener');
link.setAttribute('href', url);
link.click();
link.remove();
return;
}
$location.path(url);
}
Working on major browsers except Safari.

Window that opens and closes [duplicate]

I am using this javascript function to launch download
function startDownload(url) {
window.open(url, 'Download');
}
It works, but i want to block any new tab or new window launch, thanks.
function startDownload(url) {
window.location.href = url;
}
This will start the download in the same page, exactly like when you click a link without any target other than _self.
To force the download of a file, make sure you send the right headers with it:
Content-Disposition: attachment; filename="mypdf.pdf";
This will make sure that the file is not displayed in the browser instead of being downloaded. Replace the filename part with the filename you want as default on the save as dialog.
window.open will open a new window \ tab (depending on user preferences) ... to just download the file use
window.location.href = url;
You can use this if the url returns a downloadable file rather than a web page
HTML5 solution with 'download' attribute
<a href="/images/myw3schoolsimage.jpg" download>
https://www.w3schools.com/tags/att_a_download.asp
<a target="_parent" href="link"></a>
_blank - URL is loaded into a new window. This is default
_parent - URL is loaded into the parent frame
_self - URL replaces the current page
_top - URL replaces any framesets that may be loaded name - The name of the window

Open link in new tab when user clicks

I want to create a jQuery script that opens a specific url in a new tab if the user clicks somewhere (no matter where). After that, the user should be able to click anywhere without getting a new tab at every click again.
Unfortunately I have no idea how to create such a script, and therefore I would appreciate all your answears :)
You can use the .one() event like
$(window).one('click', function() {
var url = "http://google.com";
window.open(url, "_blank");
})
_blank in window.open() is used to open the link in a new tab.
DEMO
Refer to following links for documentation on .one() and window.open()
$(window).one('click', function() {
var url = "http://google.com";
window.open(url, "_blank");
})

Opening an url in a new tab instead of a popup (after click)

The user clicks a context-menu to create a new item, the item is saved async and a url is opened in a new tab when save is done. Thats what I want but Chrome is opening the url in a popup instead of a new tab. When opening the window outside the saveasync-then-handler it works fine (the commented code), but not inside. Anything I can do get the same behaviour inside the handler? I have tried using open.bind(this) but that didn't help...
var open = function() {
var win = window.open('/page', '_blank');
win.focus();
};
client.SaveAsync().then(open); // This doesn't work, opens in a popup window
open(); // This works, opens in a new tab
Have the same issue, it's browser protection.
Managed to solve it with a workaround:
var win = window.open('/page', '_blank');
client.SaveAsync().then(function() {
win.open('/page', '_self');
});
The trick is that it works when it's not inside an async request like a response of a http request, so we open it before the request and redirect it after we get the response.

forcing a pdf to download when clicked on button

I hava a backbonejs view containing a button saying "download pdf". I also have the url available where the pdf can be found. I want that when user clicks on the button, the pdf file gets downloaded. Is it possible?
EDIT: My view code in backbone.js
savendownload: function () {
this.$("#saveanddownload").button('loading');
var that = this;
var formData = this.fetchData();
if (formData) window.invoices.create({
buyer: formData.buyer,
items: formData.items,
company: formData.company,
action: "savendownload"
}, {
wait: true,
success: function (model) {
var data = model.toJSON();
var filename = data.filename;
//download code here
}
});
}
Don't use a button, use a link and set the href attribute to the URL of your PDF file. The browser will handle the file download for you, honoring the user's browser preferences.
<a href="your/file.pdf" />
If you need the link to look like a button, you can style it using CSS. See for example this SO thread.
Edit: AFAIK, you can't reliably initialize a file download from javascript. What you can do is to open a new window/tab with your pdf URL:
window.open("http://domain.com/document.pdf",'_blank');
But the user's browser can block the new window from being created. You might want to simply generate a download link:
$('<a>Click here to download PDF</a>').attr('href', filename).appendTo(that.$el);
And have the user click the link to initiate the file download.
use the "download" tag
<a href="assets/pdfs/yourdocument.pdf" download>Download PDF</a>
but does not wok at IE Explorer ;)

Categories