Using JavaScript to open a new window and display CSS while it loads

I am looking to utilize a new window for printing a portion of HTML content.

    var cssLink = document.getElementByTagName('link')[2];

    var prtContent = document.getElementById('print_body');

    var WinPrint = window.open('','','left=0,top=0,width=1000,height=auto,toolbar=0,scrollbars=0,status=0');

    WinPrint.document.write(prtContent.innerHTML);
    WinPrint.document.getElementsByTagName('head')[0].appendChild(link);
    WinPrint.document.close();

    WinPrint.focus();
    WinPrint.print();

However, occasionally when WinPrint is ready to perform the system print, the CSS file has still not been loaded.

Is there a solution to this issue?

Answer №1

It seems like there could be a timing issue with the browser not loading the CSS file fast enough for printing. One way to solve this is by ensuring that your printing code runs only after the CSS file has loaded successfully, as shown below:

var cssLink = document.getElementsByTagName('link')[2].cloneNode();

var printContent = document.getElementById('print_body');

var newWindow = window.open('', '', 'left=0,top=0,width=1000,height=auto,toolbar=0,scrollbars=0,status=0');

newWindow.document.write(printContent.innerHTML);
newWindow.document.close();

cssLink.addEventListener('load', function () {
  newWindow.focus();
  newWindow.print();
});

newWindow.document.head.appendChild(cssLink);

Answer №2

Maybe this solution will suit your needs.

var cssLink = document.getElementByTagName('link')[2];

var prtContent = document.getElementById('print_body');

// open _blank page view before printing
var WinPrint = window.open('','_blank','left=0,top=0,width=1000,height=auto,toolbar=0,scrollbars=0,status=0');

// add new line code here
WinPrint.document.open();
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.getElementsByTagName('head')[0].appendChild(link);
WinPrint.document.close();
// remove WinPrint.focus() and WinPrint.print() because it will call print machine of system

If you want to include CSS for printing purposes, give this a try.

@media print {
    your css here
}

For further information, check out: https://www.w3.org/Amaya/User/doc/Printing.html

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

The Angular HTML Autocomplete feature is not functioning as intended when hosted on a CDN in Chrome, despite setting it to "nope" or "off"

When setting Autocomplete to "nope" or "off" in my input box for surname, I'm still able to select from the autocomplete list. This issue occurs when accessing our Ui app through CDN at link [https:// Xyz. net], but works correctly when accessing it d ...

Aligning a picture at the center of the screen with CSS - Various screen and image sizes

For my project, I need to design a web page with a single image perfectly centered both vertically and horizontally on the screen. Here are the specific requirements: The client's screen size is unknown (mobile) The image will be user-defined with u ...

Initiate monitoring for child component modifications

I'm looking to disable 'changeDetection' for the parent component while enabling it for the child component. Can you provide an example of how this can be achieved? The parent component contains static data, meaning change detection is not ...

jQuery AJAX Concurrent Event

I have encountered a problem similar to ones discussed on SO, but none exactly match my specific issue. Here's the situation: var x = 5; if( some condition ){ $.ajax({ url:"...", success: function(response){ x = respo ...

Mobile device causing issues with sticky footer functionality

Can anyone help me troubleshoot an issue with my sticky/floating bottom footer on a calorie calculator? It works fine on desktop but not on mobile. Any ideas what might be causing the problem? HTML: <footer class="footer"> <div class="summar ...

Steps for inserting an array of strings in PHP into HTML input fields

I need help with extracting elements from a php array and displaying them as a list of text input fields on a webpage. The issue I'm facing is that the elements in the $list are strings, and when I run the code, only the portion of the string up to th ...

Discovering a CSS value using jQueryUncovering the CSS value with jQuery

Currently, I have a script that allows me to change the color of an event in a calendar to red when clicked. eventClick: function(calEvent, jsEvent, view) { $(this).css('border-color', 'red'); } Now, I want to enhance this featur ...

Locate an element within an array of strings to refine the contents of a flatlist

Currently, I have a FlatList that I am attempting to filter using multiple inputs from dropdown selectors. Here is the code snippet for my FlatList component: <FlatList style={styles.list} data={data.filter(filteredUsers)} ...

Guide to crafting a custom asynchronous function in a separate file using Express JS

I have a specific function that I want to create called: my_function.js: module.exports = function(req, res, next){ var js_obj; // Do something with the JavaScript object above // Afterwards, I want to append "js_object" to the request object: req.js ...

Step-by-step guide for integrating a Twig file in Symfony using Angular's ng-include feature

Seeking guidance in Angular, as a newcomer to the platform. I attempted to load a template within an ng-repeat loop like so, but encountered an error. I received the following error message: "Cross origin requests are only supported for protocol schemes ...

Creating a topographical map from a 3D model

<!--B"H--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Custom Terrain Heightmap Generator</title> ...

What is causing the issue with Next.js Json.map function not functioning correctly?

I am looking to develop a basic component that sources its data from a JSON list. While I am able to see the output of console.log(dat.CardId) on the website, it only works for console.log(). I cannot view the cards rendered by the .map function. The sty ...

Discovering and editing a specific line in Sheets: An in-depth look at the Message Counter

Currently, the bot checks if your ID already exists in the sheet list and adds you if it doesn't when someone writes a message in the chat. Now, I want the bot to implement a message counter in the sheet list. What would be the most effective way to ...

Having trouble getting HTML to render properly in React JS on localhost using Apache server

For the past week, I've been working on resolving an issue. I started by creating a React Application using: npm create react-app After that, I attempted to build it with: npm run build Everything seemed to go smoothly. I generated a build folder ...

the key of the global variable object is not displaying as being defined

Currently tackling some old legacy code that heavily relies on JQuery, and I'm stuck at a critical juncture. It seems like the process begins with initializing vm.products in newView = new DOMObj(). Then comes the data call, where a worker iterates t ...

Error message stating: "Node.js 'readline' - Mark-compacts near heap limit are not effective. Allocation failed."

Here's the process I'm following in the code: Primarily, I am engaging in web scraping tasks. I start by reading a text file containing approximately 3500 links. Next, I iterate through each link, filter out the ones I need, and make a request ...

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...

What is the method for initiating a POST request in Java Script without including any data?

Currently, I am utilizing Ajax to send an array to the router, as demonstrated below... var send = function () { var data = search console.log(data) $.ajax({ type: 'post', url: ...

When implementing dynatable with Meteor, the outcomes may vary between the demonstration in a fiddle and the actual application

Here is the fiddle I created for this question: https://jsfiddle.net/ereday/82wzwem8/2/ In the fiddle, you'll notice that the table header has a green background. Now, let me share the code snippet from my meteor project: simple-todos.html <head ...