Displaying an iframe in Internet Explorer

My current setup involves a button that triggers the loading and printing of a report within an "invisible" iframe enclosed in a div. This process allows users to print the report from a different page without any visual disruption or changing pages, aside from the print dialog appearing. While this method works smoothly in Chrome and Firefox, it encounters issues in Internet Explorer (IE). In IE, the parent page gets printed in its entirety, and a distorted iframe is awkwardly inserted at the bottom of the page where the iframe should be loaded.

To facilitate this process, I have an empty div named printerDiv which acts as a designated location for styling and inserting content via Javascript:

<div id="printerDiv"></div>

The JavaScript function utilized here operates upon clicking the designated button, effectively inserting the desired print page into an iframe located inside printerDiv. Once the page is loaded, it initiates the printing process:

function printPage(url) {
    var div = document.getElementById("printerDiv");
    div.innerHTML = '<iframe src="'+url+'" onload=this.contentWindow.print();>
        </iframe>';
 }

In order to conceal the div during the printing process, CSS has been implemented with absolute positioning to move it off the visible screen area. Previous attempts using display:none resulted in Firefox being unable to print iframes styled in that manner:

#printerDiv{
    position:absolute;
    left:-9999px;
}

When attempting to print in IE, the full page is printed along with a small iframe positioned at the bottom, where #printerDiv resides. The content loads correctly, but only the iframe displays while failing to hide properly. Any other content added to #printerDiv remains hidden as intended.

I've experimented with various solutions outlined in this query within my JavaScript function: experimenting with self.print and document.parentWindow.print, adjusting the styles of printerDiv to 0px height/width, all to no avail.

If possible, I am open to alternative solutions that do not involve iframes, considering IE's notable compatibility challenges. However, the primary functionality of loading invisible content and directly initiating printing via a button press must remain intact.

Answer №1

In my personal experience, I found that the key was to not hide the iframe I needed to print. If I attempted to hide it using methods like display:none or visibility:hidden, the parent page would always end up being printed instead.

Instead of hiding the frame altogether, I simply resized it to 10x10 and removed the borders. Surprisingly, this approach worked well when combined with a delay trick.

Here's a sample code snippet:

    <script type="text/javascript>
    function printFrame(frameId, targetContent)
    {
        var doc = $('#'+frameId).get(0).contentWindow.document;
        var $body = $('body',doc);

        $body.html($('#'+targetContent).html());

        setTimeout(function(){
            $('#'+frameId).get(0).contentWindow.focus();
            $('#'+frameId).get(0).contentWindow.print();            
        }, 1000);        
    }
</script>

HTML:

<div id="contentToPrint">
I want only this content to be printed
</div>
<iframe src="about:blank" id="printframe" style="border:0" width="10" height="10"></iframe>

Button for printing:

<a href="javascript:printFrame('printframe','contentToPrint')">Print This Frame</a>

Answer №2

`<script>

function framePrint(frameName) {

parent[frameName].focus();

parent[frameName].print();

}

</script>`

<a href="javascript:framePrint('FRAME123');">Print</a>

Change FRAME123 to the name of the frame that you want to print.

Answer №3

Encountering a similar issue with IE11, I found that the .focus() call was being disregarded and both the parent page and the iframe were being printed. To resolve this, I implemented a solution where a style tag was injected to hide everything except the iframe just before printing, and then remove the style after the print function was called. More details on my approach can be found at this link.

Answer №4

Encountered a similar problem with IE10 not printing the parent page but instead showing the iFrame content. The issue was resolved by adding a timeout function:

<script type="text/javascript">
function selfPrint(){
    self.focus();
    self.print();
}
setTimeout('selfPrint()',2000);
</script>

Answer №5

If you're looking to display a report in your webpage, consider implementing the following approach:

Utilize jQuery's .load() function to insert the report content into the designated element #printerDiv and style it using CSS.

In your CSS file, define the following styles:

#printerDiv{display:none;}
@media print{
    body *{display:none;}
    #printerDiv{display:block;height:100%;width:100%}
}

Include the below JavaScript code for the print functionality:

$('#printerDiv').empty().load(url, function(){
        window.print();
    }); //or use any other preferred library or plain JavaScript

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

Sequencing asynchronous functions in Angular: Ensuring one function runs before another

When working with a save function that requires you to call another function to retrieve the revision number and make an API call, both of which are asynchronous in nature, how can you ensure one function waits for the other to execute? $scope.getRevision ...

Having issues with retrieving data using findOne or findById in Express and Node JS, receiving undefined values

Currently, I am working on a microservice dedicated to sending random OTP codes via email. Below is the code for my findbyattr endpoint: router.get('/findbyattr/:email', async (request, response) =>{ try { let requestEmail = reque ...

What is the method for presenting text based on the chosen Select Option?

I attempted to achieve this using hrefs and ids, but it did not meet my requirements. This is the desired format: div.selectcountry { margin-bottom: 10px; font-family: arial; font-size: 12px; } div.countrydepartment { font-family: ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Element not found: Selenium WebDriver encountered an issue locating the element in Internet Explorer

My goal is to automate navigation to www.google.com and input some text into the search box using Selenium webdriver with Internet Explorer(IE). static WebDriver webDriver = null; static DesiredCapabilities IEDesiredCapabilities = DesiredCapabilities.inte ...

Utilizing jQuery to apply multiple classes simultaneously?

What is the purpose of allowing multiple classes to be added? Is there any real benefit to this feature or is it just unnecessary complexity? I attempted to utilize it, but found that it serves no practical function. ...

Display options through numerical selection

I have been attempting to construct something, but I'm encountering difficulties. My goal is to create a functionality where entering a number in an input field will generate that many additional input fields. I've attempted to implement this us ...

Guide to displaying a loading image when selecting an item from a dropdown menu using JavaScript

When using three drop-down lists and performing an AJAX call on each dropdown list's onclick function, I encountered a delay in loading the data. To address this issue, I attempted to display a loading image while processing the AJAX call. <form ...

The recharts error message displays: "There is no overload that matches this call."

I am currently working on developing a chart in react using the recharts library. To guide me, I am referencing an example provided in their documentation available at this link: https://codesandbox.io/s/zen-ellis-30cdb?file=/src/App.tsx While the project ...

Ways to prevent an empty iframe from triggering a load event upon injection

I have implemented a technique where I am using an empty frame to handle pseudo-asynchronous form submission. This involves referencing the frame's name attribute in the form's target attribute, allowing the form's action URI to resolve in t ...

Having issues with Angular http.post not sending data when using subscribe

I'm currently facing an issue with sending data to my API using post.subscribe. Despite the fact that no errors are being thrown, the data is not being sent successfully. It's important to note that the API itself is functioning perfectly. Belo ...

Passport JS allows you to create a secure login form that redirects users to different URIs based on their role

Currently, I am utilizing Passport JS for authentication management and Express JS to handle routing within my application. At the moment, I have a login route that directs to the /teacher URI upon successful authentication (as depicted below). app.post( ...

Making a standard AJAX request using jQuery without including the XHR header

I am looking to make an ajax-type request using the following headers (or something similar): GET example.com/ajaxapi/article/1 HTTP/1.1 Host: localhost Accept: application/hal+json Cache-Control: no-cache The key aspect here is to accomplish this withou ...

Angular: Unable to access values of non-existent data (reading '0')

I'm encountering an error when trying to import an excel file using the following code Angular Ag Grid Excel Import Cannot read properties of undefined (reading '0') I'm attempting to import a file named Book.csv, and wondering if thi ...

What is the best way to generate a new object within a function and then return it

The function performs the following steps: Retrieves an XML document through AJAX. Identifies relevant information within the document. Dynamically converts it into an object using a for loop. How can I access this generated object outside of the functi ...

Adjust the value of a JavaScript variable using Selenium

My dilemma involves a boolean JavaScript variable called foo, which is currently set to true but I need it changed to false. This particular variable has the advantage of having global scope. When using Selenium, what is the most effective method for alte ...

Sails encountering CORS preflight error due to cross-origin request

I am new to creating hybrid apps and have been following some tutorials. However, I encountered these errors on my browser console: Refused to load the script 'http://192.168.1.142:35729/livereload.js?snipver=1' due to Content Security Policy di ...

MUI: The fontFamily property is not able to be overridden by nesting within the

My goal is to have different fonts for different parts of my application using theme nesting. Unfortunately, I discovered that theme nesting doesn't work when it comes to overriding fonts. In my App.js file: import React from "react"; impor ...

How can PHP be used to decode JSON and transmit it to Javascript?

I am aiming to utilize the Twitter API in order to dynamically populate slides on a webpage with recent tweets without needing to refresh the entire page. Currently, my approach involves making an AJAX call every few seconds from a JavaScript function on ...

Obtain a Spotify Token and showcase information in next.js

This is a Simple Next.js component designed to display the currently playing song on Spotify. Context: Utilizing app Router Due to Spotify's token requirements necessitating a server-side call, the entire request is made to fetch the song from an ...