What is the best way to attach a PDF file in AngularJS?

Within the code snippet provided below, there exists a hyperlink that triggers the opening of a PDF generated by Spring in a new browser window upon user interaction. However, certain users may have their pop-up blockers activated in their browsers. What specific modifications are required in the following code to ensure that the PDF opens IN THE SAME BROWSER WINDOW when the link is clicked? Please take note that this PDF is generated via a spring controller.

The HTML snippet is as follows:

<p><a ng-click="getPdf()">Show PDF</a></p>

Below 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);
          });
    }
});

Answer №1

window.open has the ability to support a second parameter called windowName. By setting this to "_self", you can open the URL in the same window.

window.open(fileURL, "_self");

To learn more, visit this link.

An alternative approach could involve updating the directive's links' href to the correct URL before navigation. This would allow you to use _blank as the target and open it in a new tab/window.

Answer №2

When it comes to opening a new window using JavaScript, it's important to consider providing users with a clickable link that directs them to the desired destination. This can be achieved by setting the href attribute of the anchor tag to the corresponding file URL. To ensure a smooth user experience, you can choose to either generate the PDF document in advance or offer a separate link for download after the PDF has been created.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues while attempting to harness the power of Ajax, Spring, REST, and JAXB for

Encountering errors while attempting to utilize Ajax, Spring, REST, and JAXB. The objective is to make a REST call from Ajax to Spring. Below are the errors being faced: This is my JSP file: <%@ page language="java" contentType="text/html; charset=UTF ...

Cease the execution of promises as soon as one promise is resolved

Using ES6 promises, I have created a function that iterates over an array of links to search for an image and stops once one is found. In the implementation of this function, the promise with the fastest resolution is executed while others continue to run ...

To obtain the desired response, I must make an additional GET request

Upon sending the first GET request to this endpoint, I receive a response of allEvents = []. However, if I wait a few seconds and hit the endpoint again, I get the desired results with a populated allEvents array. It seems that the function is not executin ...

Exploring the architecture of Redux-thunk and validating the impact of side effects

I've been using redux-thunk and I'm not entirely sure if my side effects (specifically the showAlertError function) are structured properly. While my jest test setup seems to be fine at first glance, I encountered an error: jest.fn() value mus ...

How to retrieve and modify JSON data in Node.js using Stream with both Get and Post methods

Exploring Node.js for the first time, I'm currently tackling a project where I aim to utilize Request for streaming data from one endpoint to another. The objective is to leverage Request for extracting and posting an altered JSON body through a pipe ...

Deleting all JSON files in a directory using NodeJs

Is there a way to delete only the json files within a directory (multiple levels) without specifying each file name individually? I thought fs-unlinkSync(path) might work, but I haven't found that solution yet. I attempted to use the following method ...

Replace automatically generated CSS with custom styles

When using a Jquery wysiwyg editor, I have encountered an issue where it automatically adds code to the textarea at runtime. The problem arises from it inserting an inline style of style="width:320px" when I need it to be 100% width due to styles already ...

Momentjs initially indicates that the date is valid, logs the correct date, and displays the accurate duration using .fromNow(). However, this suddenly switches

I am currently working on converting the createdAt date in my Nuxtjs application that is fetched from MongoDB using an express app, with the help of moment.js. Initially, when I check if the date is valid, it shows as valid but then it switches to an incor ...

Difficulty executing for loop due to multiple buttons, resulting in malfunctioning buttons in JavaScript code

Currently encountering an issue while trying to implement modal windows on my first website. Everything works fine without the for loop, but I wanted to have multiple buttons and windows, so I decided to use a for loop to handle each button. Strangely, the ...

Experiencing trouble with setting values in JavaScript?

I have my code set up to display numbers 170 and 122 using Javascript, but I'm not seeing the expected output. <!DOCTYPE html> <html> <body> <button onclick="UidToPost()">Get It</button> <script> ...

Is there a way to turn off vue.js transitions specifically for testing purposes?

I'm utilizing a vue.js component with the <transition> element for show/hide animations. However, I want to disable the animation for faster testing. How can I achieve this? The solution proposed is * { transition: none !important } in this lin ...

The beforeRouteEnter callback function fails to trigger

I'm encountering an issue with my simple routes: /follower/:token/edit and /follower/new Whenever I navigate from the first route to the second one using $router.push('/follower/new'), the beforeRouteEnter hook is triggered, but the callbac ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

Is there a way to send the element as an argument within the inner function?

I need to pass the selector as a parameter through the Slider to an Object nested function. I anticipated that istouchEnd would receive the .storage1 as a parameter from the Slider, but unfortunately, this.storage never gets the parameter from the Slider ...

Error: Cannot execute products.map in React JS because it is not a function

I'm encountering a TypeError: products.map is not a function error while attempting to iterate or map through the objects in my current state. I am fetching products from an API and storing them in state with the intention of displaying these objects. ...

Retrieve the file path of the local system's home directory from the server

The server is up and running, I am looking to retrieve the file path of the local system in which the AWS server is operating using Node.js. ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

My intention is to ensure that the page is printed with the Background graphics checkbox pre-checked

When using the print button, I typically include the following code: onclick="window.print();" I also came across this code snippet to set a checkbox as checked by default: <style type="text/css" media="print"> * { -webkit-print-color- ...

Error: The 'in' operator cannot be utilized to search for 'length' in the Kendo UI framework

I am encountering an error while using Angular 1.4, jQuery 1.11.3, and the latest Kendo UI. I'm wondering if this issue is a known bug to Telerik. The only Kendo controls present on the page are kendo-multi-select and kendo-date-picker. TypeError: C ...

Strategies for transferring a dynamic variable to a parent window's form in JavaScript?

What is the best way to use a changing parameter name when accessing a variable? For instance: opener.document.form.namerow_3.value = this.cells[0].innerHTML; opener.window.form.{varaible}.value=this.cells[0].innerHTML; In this scenario, the parameter ...