Saving base64 encoded pdf on Safari

I am facing an issue with a POST call that returns a base64 PDF. The problem arises when trying to convert it to a Blob and download it using Safari browser. This method works perfectly in all other browsers.

openPdf = () => {

  const sendObj = {
    fakeValue: 'test'
  };

  axios.post('https://fakeendpoint.com/create-pdf', sendObj)                
    .then((res) => {
      const base64URL = res.data;
      const binary = atob(base64URL.replace(/\s/g, ''));
      const len = binary.length;
      const buffer = new ArrayBuffer(len);
      const view = new Uint8Array(buffer);

      for (let i = 0; i < len; i += 1) {
        view[i] = binary.charCodeAt(i);
      }

      // creating the blob object with content-type "application/pdf"
      const blob = new Blob([view], { type: 'application/pdf' });
      const url = URL.createObjectURL(blob);

      const a = document.createElement('a');
      document.body.appendChild(a);
      a.style = 'display: none';
      a.href = url;
      a.download = 'Test.pdf';
      a.target = '_blank';
      a.click();
  });
}

Any suggestions on how to make this function properly in Safari?

Answer №1

It appears that Safari is not adhering to the standards for the a tag. A previous discussion on Stack Overflow (found at this link) seems to have pinpointed the issue. According to comments in the linked post:

It's important to note that specifying a target attribute in Safari might override the download attribute, unlike in Chrome, Firefox, or Opera.

One possible solution would be to remove the line a.target = '_blank' from your code and test it again. This adjustment should resolve the problem!

However, if you rely on opening the link in a new tab, it may require further exploration for an alternative method.

Answer №2

During my testing, I discovered that this issue only arises when the PDF file is too large, and specifically on mobile Safari. My hypothesis is that it has to do with the length of the URL.

An alternative solution could be removing the target="_blank" attribute, but one downside to consider is that users may lose their previous page state if they click the "back" button.

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

Chrome and Firefox: Images cling together

I've encountered an issue with my recently launched website. Some images in a grid appear to be stuck together, but this problem only occurs in Firefox and Chrome browsers. Oddly enough, zooming in to around 110% then back to 100% seems to temporarily ...

"Adjusting the height of Material UI card content to ensure fixed positioning at the bottom

Currently, I am working on mapping material-ui cards with dynamic content from a JSON object, resulting in varying card heights. I have successfully set a fixed height for each card, but the content is not aligned correctly. You can see the issue in this ...

When trying to click on an HTMLTableRowElement, an Uncaught ReferenceError occurs in React.js and jQuery, stating that the function is

When I was working on my web app, I encountered an issue while trying to create a table. Upon clicking on it, I received an error message: Uncaught ReferenceError: (function) is not defined at HTMLTableRowElement.onclick Here is the code for the table: $( ...

How to use the handleChange() function in React with various state properties

Explaining a bit about the handleChange function, which takes the name of the state element to be associated with it. Is there a specific reason why it has to be structured like this: handleInputChange(property) { return e => { this.setSta ...

Issue with Laravel 5.4: AJAX behaving unexpectedly and not returning errors as it should

After going through several tutorials on handling AJAX requests in Laravel, I'm still facing some issues. Each tutorial has its own approach... Finally, one method is not giving me a 500 error, but it's not displaying validation errors as expect ...

Create a form in a React component that allows the user to input information

My challenge is to create a functionality where each time the add button is clicked, it should dynamically add an input field that I can save. It's similar to this example, but with inputs instead. The complexity arises from the fact that the inputs a ...

Why won't the button's color change when I try clicking on it?

I am currently learning vue and facing some challenges. The code I have is supposed to change the button color when clicked, but it's not working as expected. Any advice on how to fix this issue would be greatly appreciated. Thank you! let app = ...

`Struggling with managing callbacks, handling errors, and working with MongoDB`

I recently revamped my code for an application that handles adding companies to a database. In the past, my code was messy and unorganized, so I decided to structure it properly by introducing routes, a controller, and a data access object. Here is how my ...

Stacking items when clicked on with jQuery UI Draggable

Can a draggable's stack procedure be activated by clicking instead of just dragging? I came across this solution, which essentially replicates the library code (with an important addition I included below). Is there a more elegant approach to achieve ...

Monitor files in different directories with the help of pm2

Can pm2 detect changes in directories outside of the current one? For example, if I have an index.js file in /home/sprguillen/workspace/node that needs to be run by pm2, but my configuration file is located outside in /home/sprguillen/workspace/config. I ...

Updating the row by substituting the content of two columns with the data retrieved from the action class

In my JSP page, there is a table with a refresh button on each row. Upon clicking the refresh button, a JavaScript/AJAX call is made to an action class to retrieve the values of status and number of records for that row, which are then displayed in the cor ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

Vue - a guide on customizing a prop in a parent component

I have implemented a wrapper component that encapsulates a Quasar q-select element in the following manner: <template lang="pug"> q-select( :options="organisations" option-value="id" v-bind="$attrs&quo ...

Angularjs - Repeatedly reloading identical images

Whenever I use ng-src in the <img> tag and change the ng-src by clicking next or previous buttons, the browser reloads the image even though it's already loaded. This results in a not-so-smooth experience as the image is downloaded again before ...

Utilizing Sequelize's Where clause with the flexibility of optional parameters

Can you guide me on writing Sequelize queries with optional parameters? Consider the below query example: const result : SomeModel[] = await SomeModel.findAll( {where: { id: givenId, ...

Attempted to utilize zipstatic but received no feedback

I attempted to utilize the Zipstatic API with jQuery in my code, as shown below. However, I am not receiving any response. Could there be something missing? jQuery(function() { jQuery("#form").hide(); jQuery("#postcode").keyup(function() { var c ...

Guide to selecting an element with a combination of text and a random number using Selenium with JavaScript

<a id="Message4217" class="btn-sm btn-danger Message" data-id="4217"><span class="icon-adjustment icon-trash"></span> Delete</a> The objective is to remove a message base ...

Tips for Loading a Selected Option from an Ajax Call in Angular JS on Page Load

How do I automatically set the selected option from an ajax call when the page loads? I am fetching zones using an ajax call and I want to trigger the change function of the zones on page load in order to set the selected option of the cities select box. ...

What is the best way to auto-fill input fields with data from a Json file

My goal is to automatically populate HTML form fields based on user selection. I have obtained code for related functions, such as fetching JSON data and creating dropdown lists, from a friend. Here is the link to that code: https://jsfiddle.net/r4zuy7tn/1 ...

Tips on locating information within a pre-existing GET array with parameters provided

Apologies for the unclear title. I am currently utilizing a category chooser that pulls categories from an API. The process involves fetching a list of categories, filtering out their names, and presenting them in the category chooser. Upon clicking submit ...