Creating HTML content in a new window with Vue.js - a step by step guide

Recently, I encountered a problem with jsPDF regarding Unicode support in table generation. To work around this issue, I decided to utilize the browser's print feature instead. I achieved this by creating a new HTML document with the table and displaying it as a popup, then calling popup_window.print() as shown below:

//exporter.ts

  const temp = document.createElement("div");
  temp.innerHTML = tableHtml(
    tableHead,
    tableBody,
    fileName
  );
  const popup_window: any = window.open(location.origin, fileName, "x=y");
  popup_window.document.write(temp.innerHTML); 
  setTimeout(() => {
    popup_window.print();
    popup_window.close();
   }, 1000);

// tableHtml.ts

const tableHtml = (
  headers: string[],
  records: GeneralOBJ[],
  title: string,
  direction = "rtl"
) => `<!DOCTYPE html>
<html>
<body>
<main id="main" style="direction: ${direction};">
<h1>${title}</h1>
<div class="app_table">
<table class="table">
 <thead>
  <tr>
    ${headers
      .map(header => "<th class='col' dir='auto'>" + header + "</th>")
      .join("")}
  </tr>
</thead>
<tbody>
  ${records
    .map(
      record =>
        "<tr>" +
        Object.values(record)
          .map(td => "<td dir='auto'>" + td + "</td>")
          .join("") +
        "</tr>"
    )
    .join("")}
</tbody>
</table>
</div>

</main>

</body>
</html>`;

While this method works well, there are potential security risks such as xss vulnerabilities. To address this, I am considering using Vue.js to generate this piece of HTML content and then incorporate it into temp.innerHTML. Do you have any suggestions on how to achieve this securely?

Answer №1

VueJS serves as a powerful Single Page App tool, consolidating all elements into one cohesive HTML document. While it is feasible to operate multiple Vue instances across various HTML pages, synchronization of shared data or store is essential.

An effective strategy involves creating a component housing popup content, subsequently initiating an additional Vue instance on the popup window to mount the said component. For guidance on programmatically generating Vue component instances, refer to this insightful resource on CSS tricks.

In scenarios where simplicity is paramount, exploring alternative libraries can often offer quicker solutions. For tasks involving unicode compatibility, consult resources like this informative discussion on Stack Overflow for assistance with unicode support in PDF generation.

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

Error: JSON data couldn't be processed due to an unexpected end, resulting in a SyntaxError at JSON.parse()

I'm currently working on making an ajax call to an API, but I keep encountering an error whenever I try to make the call. I've been troubleshooting this for hours and I can't seem to figure out what the issue is. At one point, I even removed ...

The function "onClick" within an external .js file is being referenced

Just starting to learn Javascript and experimenting with an onClick event for an image in an external .js file using the HTML tag. <script type="text/javascript" src="embed.js"> The code found in "embed.js" is as follows: var image1=new Image(); i ...

Encountering a Vercel deployment failure due to a TypeError: The 'split' property cannot be read from undefined within several objects

I'm having trouble deploying my web application for the first time and encountering this error on Vercel: TypeError: Cannot read property 'split' of undefined at Object.3qS3 (/vercel/path0/.next/serverless/pages/[collection]/[templateId].j ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Utilizing component state or props within Redux mapDispatchToProps operations

As a newcomer to Redux/React, I am still grappling with the concept of dispatch in the Redux environment. Currently, my approach to issuing Redux actions within components involves directly calling the dispatch() function from my component props: const ma ...

Identifying and Blocking Users from Accessing External Domains Outside of the Angular Application

I am working on an angular application and I need to implement a feature where I can detect when a user navigates outside of the app domain from a specific component. For instance, let's say the user is on the upload component processing important in ...

Exploring options for accessing Google Maps API on iPhone without using UIWebView for processing JavaScript

I need to retrieve data from Google Maps using JavaScript, without using a webview. For example, I have two points (lat,lng) and I want to use the Google Maps API to calculate the driving distance between them. Essentially, I want to utilize the Google Ma ...

Sending JSON data to the server using jqGrid: A step-by-step guide

[CHANGE] (I couldn't bear to wait 3 hours for an answer): It seems that the issue is not with the jqGrid component, many thanks to TheCodeDestroyer for identifying this. I ran this code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "h ...

Vue is lagging behind in implementing Virtual Dom technology

I have come across this code snippet. <template> <div ref="nodesData"> <div v-for="(item, index) in nodes" :key="index" :id="item.id"> {{ item.id }} </div> <div> ...

Retrieving information from a local JSON file in Vue.js using the jQuery $.getJSON() method

Currently, I am in the process of developing a demo application using Vuejs which involves extracting map data from a local .json file. The extracted data is then used to obtain specific information like latitude and longitude values that are necessary for ...

Transferring environment variables from Azure pipelines to a Vue application using Quasar 2.6 with a readonlyrootfilesystem configuration

I am currently working on a Vue App that is powered by Quasar 2.6. I recently made a configuration change in my AWS task definition to set readonlyrootfilesystem to true. However, I encountered a problem when trying to write environment variables to a file ...

Having trouble parsing a JSON string in your JavaScript code?

As a java developer transitioning to JavaScript, I'm faced with the task of parsing a JSON string retrieved from a WebService. Here is the JSON String: { "myArrayList": [ { "myHashMap": { "firstName": "Clara", ...

Is it possible to perform a forEach operation on two separate arrays simultaneously?

I have created two arrays and then utilized a function to assign values to certain variables based on the element clicked in the array. (Refer to the first code snippet) However, I am now looking to execute another function that makes use of these assigned ...

Effortless JSON parsing with Angular 2 Http GET request

After sending an HTTP get request to my server API, I am attempting to parse the JSON object that is returned. Below is the code snippet for the Http call: getPayoutReport(param1, param2, param3) { //perform necessary actions //set up a requestUr ...

Issue with repeated items in Flatlist

Whenever I display my flatlist, it appears to be duplicating the items within it (the feedCache has only one index but the data for this index is rendered twice). Below is the code snippet for the flatlist: const FeedBody = React.memo(() => { return ...

Using the .get() method to retrieve Firebase documents results in an error message saying "'is not a function'"

I'm currently attempting to retrieve all the documents from a specific collection in Firebase using the following code snippet: const userCollectionRef = collection(db, currentUser?.uid) const snapshot = await userCollectionRef.get() for (const doc of ...

Executing synchronous animations in Jquery with callback logic

My jQuery plugins often rely on user-defined callbacks, like in the example below: (function($) { $.fn.myplugin = function(options) { var s = $.extend({}, options), $this = $(this); if (typeof s['initCallback'] = ...

Tips on preventing the opening of a new browser tab by using Ctrl + click

Hey there, I've got a list of products that can be selected using the Ctrl key. $(parentSelector).on("click", function (evnt) { evnt.stopImmediatePropagation(); var item = $(evnt.delegateTarget) ...

Stagnant variable value after onClick event

After exploring various solutions, none seem to quite fit my needs. I want to update the variable "currentIndex" when a user clicks on an image. Currently, the change occurs within the onClick function but does not affect the outside variable. I am unsur ...

Inspecting the Nuxt.js application, retrieve the build version using console.log

Currently, my Nuxt site is being hosted on AWS S3 with Cloudfront. Whenever I deploy a new version, I have to invalidate the CloudFront CDN which causes a delay in the deployment process. I want to display the build hash by using console.log(buildHash) wh ...