Chrome preventing PDFs from being viewed on web pages by redirecting to a new tab with Top-Frame Navigations

Due to recent updates in Chrome version >=60, the ability to view PDF files through top-frame navigation options such as

<A HREF=”data:…”>
window.open(“data:…”)
window.location = “data:…”

has been blocked by Google. Discussions regarding this can be found on Google Groups. The issue now is how to display PDFs on the web without forcing them to download. Previously, I used window.open to view PDF data like this:

dataFactory.getPDFData(id, authToken)
.then(function(res) {
    window.open("data:application/pdf," + escape(res.data));
},function(error){
    //Some Code
}).finally(function(){
    //Some Code
});

In the above code snippet, I fetched and displayed PDF data from the server. However, since Chrome now blocks window.open, I followed suggestions from an expert on here to use <iframe> for displaying PDF data, but it's not working as expected. It consistently shows "Failed to Load PDF Data" message.

The updated JavaScript code using <iframe> is as follows:

dataFactory.getPDFData(id, authToken)
.then(function(res) {
    $scope.pdfData = res.data;
},function(error){
    //Some Code
}).finally(function(){
    //Some Code
});

And the corresponding HTML looks like this:

<iframe src="data:application/pdf;base64,pdfData" height="100%" width="100%"></iframe>

I am struggling to bring back the original functionality of viewing PDFs. I have searched other stack questions but haven't had any success yet. It seems like there might be a mistake or missing detail in the iframe implementation that I need to fix.

Answer №1

Struggling to find a solution, I devised a unique approach to tackle the problem at hand. Rather than opening the PDF in a new tab, I implemented a feature where clicking on the Print button would automatically trigger the download of the PDF file. Here is the code snippet detailing this innovative solution:

//Specifying File Name
var fileName = "Specify File Name Here";

//Creating an array to hold binary data
var binaryData = [];
binaryData.push(serverResponse.data);      //Regular pdf binary data needs to be pushed within an array

//Converting PDF binary data to downloadable file
var file = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
var fileURL = document.createElement("fileURL");
fileURL.href = file;
fileURL.download = serverResponse.name || fileName;
document.body.appendChild(fileURL);
fileURL.click();

//Removing the added element once the task is completed
window.onfocus = function () {                     
    document.body.removeChild(fileURL)
}

Answer №2

When looking at your previous code : "data:application/pdf," + escape(res.data)

In the updated version : the src attribute of your iframe should be structured as "data:application/pdf;base64,pdfData"

Consider eliminating 'base64' from the src, as it appears to be included in the value of 'pdfdata' already.

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

Develop a cutting-edge front end for Hyperledger Fabric 2.2 with React js and enhance it with a node

Currently, I have developed a unique hyperledger fabric 2.2 blockchain network using javascript and am looking to integrate it with a React.js front end utilizing the node.js API. Despite my efforts to find relevant examples, most resources focus on hyperl ...

Exploring the functionality of buttons within jQuery Impromptu

My current project involves creating a survey composition tool. The main focus is on having a preview button that displays the values inputted by the user. <!doctype html> <html> <head> &l ...

Is it possible to use jQuery's .attr method to change the href attribute if a certain text is contained within a DIV

(Twitter) I'm struggling with how to incorporate the .attr method at the start of links/A/href when the selected element contains specific words: $(".tweet:contains('government','Anonymous')").each(function(){ $old_url = $(thi ...

if there is an error in a JavaScript statement

<!DOCTYPE html> <html> <head> </head> <body> <hr> <div> <div id="myPosition"> </div> </div> <hr> <!--Storing the gun array --> <div id ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

Incorporating input utilities into a text field

Currently working on a Django blog website catering to bloggers who are not well-versed with Markdown/Markup. I am considering incorporating these tools into my textarea, as shown in the image below: https://i.sstatic.net/ud4hV.jpg Any recommendations on ...

Utilize dropdown selections to generate a custom function for calculating prices using JavaScript

Currently, I am facing a challenge in writing the calcTotal function as I am uncertain about how to distinguish between the selected pizza and the quantity of pizzas requested. My goal is to assign specific prices to each type of pizza (Cheese $6, Pepperon ...

Using Angular to bind the ngModel to a variable's object property

In my application, I am working with a user object that looks like this: let user = {name: "John", dob:"1995-10-15", metadata: {}} The metadata property of the user object is initially empty. I want to add a new property to the metadata object based on u ...

Implementing THREE.js (along with THREEx and AR.js) CDN into my React component: A step-by-step guide

I found that using React for projects like this can be less cumbersome than Angular, and you can still incorporate "plain" JavaScript into your project. In my react project's index.html file, I have added the following script tags in order to integrat ...

Sending an array as a query string

I am trying to send an array to my server using jsonp. Here is an example of the JSON I want to pass: ["something","another_thing",4,{"iam" : "anobject"}] However, I am unsure about how to actually pass an array. I thought it might work like this: some ...

Vue-js-modal not displaying Dropzone.js

I'm currently working on a project that involves using both the vue-js-modal plugin by euvl and dropzone.js for handling multiple file uploads. My goal is to integrate both libraries so that users can open a modal window and upload files. However, I& ...

Exclude specific fields when updating a document in Firebase using the update()

Currently, I am storing a class in Firebase by using the update() function. Is there a way to stop specific fields (identified by name) of the object from being saved to the Firebase database? It's similar to how we use the transient keyword in Java ...

Guide to exporting several Chart.JS graphs to a PDF document with each graph on a separate page

I am currently utilizing the JavaScript code provided below to generate a pdf file containing multiple charts. However, all the charts are being placed on a single page. My inquiry is regarding how I can customize the code to have each chart on its own sep ...

The value is not being populated in the text area when the onchange event occurs

<textarea className="form-control queryheight box_xp" placeholder="Enter Dashboard Content" type="text" onChange={this.dashboardtextchartchange.bind(this)} value={this.state.textdashboard}> </textarea> Function triggered on change : dashb ...

There seems to be a problem with the full calendar updateEvent feature as it is unable to read the property 'clone'

Struggling to update an event using FullCalendar and a modal. Encounter the 'cannot read property 'clone' of undefined' error when attempting to update. Following the documentation, I utilize the clientEvents method. It is crucial t ...

Implementing an ES6 class in a next.js application: A step-by-step guide

Currently, I am in the process of developing a next.js application and am looking to extract the code that interacts with the database from the API. To achieve this, I have developed a class that serves as a manager: class UserManager { async findUser ...

Examining AngularJS Jasmine Promises in IsolationDive into the world

Seeking help for testing a mocked Service with chained promises. Factory for Testing app.factory('factory', [ 'service', function( service ){ var baz; return { updateMe: function( updateObj ){ // do stuff with upd ...

Insert the ng-if directive into an element using a directive

I am working on an AngularJS directive that involves looking up col-width, hide-state, and order properties for a flexbox element based on its ID. I want to dynamically add an ng-if=false attribute to the element if its hide-state is true. Is there a way ...

When the enter key is pressed, shift the text to a different input field

I am facing a complex requirement How can I detect the pressing of the ENTER key within a text box with the following conditions: If the cursor is at the end of a sentence, it should create a new text box on the next row. If the cursor is in the middle ...

Can the combination of a JavaScript frontend and NodeJS backend function effectively together in this scenario?

I have a Domain-A that serves as a static site on Netlify, offering shopping cart functionalities. On the other hand, I have Domain-B hosting a backend server running a Node.JS payment system and utilizing Auth Services through passport.js. Due to its na ...