Tips for retrieving document body from a script embedded within document.write

I urgently need assistance! I am currently developing an application that retrieves a report from an API, and the JSON response includes HTML content. Unfortunately, due to the JSON format, I cannot directly open this in a new browser window.

Within my script, I am incorporating the following code snippet:

          let tmp = result.data;
          let spot = tmp.indexOf('</body>');
          let insert = `<div style="position:fixed; top:200px;left:20px; width:200px;font-size:15pt">
         

          <div class="camera">
            <video id="video" style='display:hidden'>Video stream not available.</video>
            <button  onClick='takepicture()'>Take photo</button> 
          </div>
          <canvas id="canvas" style='display:none;'></canvas>
        <!--<button onClick='genPDF()'>PDF</button>-->
          Press CTRL+S to save page as HTML
          <img id="testDownloadImage" src='' width=600 height=400 />
          </div>
          
          <script type='text/javascript'>
alert(document.body.innerHtml)
          // function clearphoto() {
          //     var context = canvas.getContext('2d');
          //     context.fillStyle = "#AAA";
          //     context.fillRect(0, 0, canvas.width, canvas.height);

          //     var data = canvas.toDataURL('image/png');
          //     // photo.setAttribute('src', data);
          //   }
            
            // Capture a photo by fetching the current contents of the video
            // and drawing it into a canvas, then converting that to a PNG
            // format data URL. By drawing it on an offscreen canvas and then
            // drawing that to the screen, we can change its size and/or apply
            // other changes before drawing it.

            async function takepicture() {
              let video = document.getElementById('video');
              let canvas = document.getElementById('canvas');

              let displayMediaOptions={video: true,displaySurface:'browser', logicalSurface:true, cursor:'never', audio: false};
              try{
                video.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
                // video.play();
                var context = canvas.getContext('2d');
                width=window.innerWidth;
                height=window.scrollHeight;
                if (width && height) {
                  canvas.width = width;
                  canvas.height = height;
                  context.drawImage(video, 0, 0, width, height);
                
                  var data = canvas.toDataURL('image/jpg'); //.replace(/^data:image\/(png|jpg);base64,/, "");
                  // photo.setAttribute('src', data);
                  document.getElementById('testDownloadImage').src=data;
                  // location.href=data;
                } else {
                  // clearphoto();
                }
              }
              catch(err) {
                console.log("An error occurred: " + err);
              }
              finally{
              let tracks = video.srcObject.getTracks();
              tracks.forEach(track => track.stop());
              video.srcObject = null;
              }
            }
        </script>
          `
          let newStr = [tmp.slice(0, spot), insert, tmp.slice(spot)].join('');
          document.write(newStr);

This implementation is essential for adding a print screen feature to capture images of the report. Despite trying various tools to convert the HTML to PDF or saving the entire page, these methods have proven ineffective due to the extensive XSLT and scripting used in displaying the results, leaving me with no choice but to resort to using the print screen option.

While WebRTC effectively addresses this issue, there is one minor challenge: The use of document.write hinders me from accessing the document.body, even though the provided code represents a properly structured page.

How can I leverage the embedded script to render and capture the page as an image successfully?

Your help is greatly appreciated!

Answer №1

I encountered a similar issue, but found a creative solution by implementing an iFrame and moving the script outside of it. By adjusting the height of the iFrame to match the scrollHeight of its document, I was able to create the illusion that the content spanned the entire page. This allowed me to achieve my goal of capturing the entire page while keeping the script separate from the main content.

Appreciate any feedback or suggestions on this approach. It seems to have resolved the issue for now.

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 combination of Node.js, Express, and Angular is causing a continuous loop in the controller when a route is

Currently, I am utilizing node js alongside Express. Angular js files are being loaded through index.html. The code for app.js is as follows: app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); ...

Setting up Redux Saga in a modular format

I am currently using create-react-app for my project. As I now need redux-saga to handle async operations, I am encountering an issue with setting up sagas in a modular manner. When I say modular, I mean having one main sagas file that exports all the comp ...

Update the useMemo state value after the initial function block has been executed

Currently, I have a list of characters from Dragon Ball Z that users can filter based on gender, race, or both using useMemo. let dbzCharacters = useMemo<CharacterObj[]>(() => { if (filterGenderValue && filterRaceValue) { retur ...

The script tag in NextJS is not properly loading the Amplitude library

I am facing an issue with loading events using Amplitude JS for tracking, despite having the correct code in place. Here is the code snippet that I used: import Document, { Html, Head, Main, NextScript } from 'next/document'; import Script from & ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...

How to properly format JSON responses in Node.js or Express

I came across a question on Proper way to return JSON using node or Express and copied it for reference. I am looking for the response in a specific format. This is the sample format for the response API: { "success":true, "code":200, "message":"Ok", "da ...

Obtain the position and text string of the highlighted text

I am currently involved in a project using angular 5. The user will be able to select (highlight) text within a specific container, and I am attempting to retrieve the position of the selected text as well as the actual string itself. I want to display a s ...

Move files into the designated folder and bundle them together before publishing

Is there a way to transfer the files listed in package.json (under the File field) to a specific folder in order to bundle them together with npm publish? Here is the structure of my repository: . ├── package.json └── folder0 ├── fil ...

Using tabs within a Dialog prevents the Dialog from adjusting its height automatically

Solved: Find the solution in the comments section below. I recently built a Tabs feature within a Dialog box, but ran into an issue where the height of the Dialog did not match up with the height of the tab. The problem arose when a form was placed insid ...

Place a material-ui React component at the center of a footer section

I'm facing a challenge with centering a material-ui Simple Breadcrumbs component within a footer as opposed to having it aligned to the left. Even though I'm new to this, I thought it would be straightforward but I can't seem to figure it ou ...

Optimizing the performance of "document.createElement"

When attempting to display multiple rows of data in a popup using a for loop, I initially utilized text strings to create and append the div elements. However, I discovered that using document.createElement resulted in a 20% improvement in performance. D ...

Default parameter in Node.js is set when the callback function is the last parameter

Here's a simplified version of the function I'm working with: doSmthg (name, age, callback) { callback(name, age); } I want to set a default value for age if it's not provided. In ES6, I could do doSmthg(name, callback, age=42) {...}, b ...

Persist the data retrieved from an asynchronous function in the memory

I am faced with a challenge in Node.js where I need to store an object in memory. This particular object is created asynchronously from an API call. The issue at hand is that previously, this object was synchronous and many parts of the application were de ...

Determine the number of rows in the Tabulator's table

Can anyone tell me how to retrieve the number of rows in a table created using Tabulator on a website? Is there a method like table.size or table.length that I can use for this purpose? The table has been initialized with the following code: table = new T ...

Picture is unavailable for viewing - (Express, Pugjs)

I'm having trouble getting an image to display on my page using a pug template. Despite following the setup and files correctly, the image still isn't showing up. Here is what I have: index.js app.use('/images', express.static(path.r ...

Effortlessly handle form submission with jQuery AJAX, automatically redirecting upon successful

I am working on a project using ASP.Net MVC where I have a view that submits form data to a controller action. In order to make this form submission more dynamic, I am trying to utilize jQuery to post the form via an AJAX call with the following code: $(" ...

Dismiss Bootstrap by clicking anywhere

I have a specific input that is displayed when clicked and disappears with the next click: <a href="#;" class="asset_info" data-asset_id="{{ asset.pk }}" data-toggle="focus" tabindex="0" data-placement="left" data-trigger="focus" >Hello</a> ...

The "read more" button seems to be malfunctioning

I've been working on integrating a gallery of images into my posts. My goal is to display 4 images initially, followed by a "load more" button that, when clicked, will reveal another set of 4 images, and so on. I have already created the HTML, CSS, an ...

What is the best way to ensure that a navbar dropdown appears above all other elements on

I'm having trouble creating a navbar dropdown with material design. The dropdown is working fine, but the issue I'm facing is that other elements are floating above it. https://i.stack.imgur.com/aJ0BH.png What I want is for the dropdown to floa ...

Mandatory press for a function known as a click

After dealing with a previous question on this matter, I have encountered yet another issue. My goal is to rotate an element clockwise by 22 degrees and then back to its initial state of 0 degrees on click. The first function executes correctly, but the ...