html2canvas issues chrome extension

I am trying to use the html2canvas within a chrome extension I am building.

For my chrome extension I am directly injecting JS so that the user can toggle the extension so it does not go out of focus and closes when the user clicks on the current tab.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
<body>
<script src="popup.js"></script>
</body>
</code>
<code> <body> <script src="popup.js"></script> </body> </code>

<body>
    <script src="popup.js"></script>
  </body>

I am choosing to dynamically load the html2canvas from a local file where I have copied the JS file.

I am loading it within my content.js file (this file also contains the UI where it is directly injecting into the current tab DOM.

Here is the function where I am calling the html2canvas to load:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> async function mouseUpHandler(e) {
if (!isSelecting) return;
isSelecting = false;
// Remove event listeners and overlay
const overlay = document.getElementById("selectionOverlay");
overlay.removeEventListener("mousedown", mouseDownHandler);
overlay.removeEventListener("mousemove", mouseMoveHandler);
overlay.removeEventListener("mouseup", mouseUpHandler);
document.body.removeChild(overlay);
// Get the selected area coordinates
const rect = selectionBox.getBoundingClientRect();
// Remove the selection boxhtm
selectionBox.remove();
console.log("Selected area:", rect);
try {
// Wait for html2canvas to be loaded
await loadHtml2Canvas();
// Ensure window.html2canvas is loaded and then use it
window.html2canvas(document.body, {
x: rect.left + window.scrollX,
y: rect.top + window.scrollY,
width: rect.width,
height: rect.height,
windowWidth: document.documentElement.scrollWidth,
windowHeight: document.documentElement.scrollHeight,
scale: window.devicePixelRatio // Adjust for high-DPI screens
})
.then((canvas) => {
const dataUrl = canvas.toDataURL("image/png");
console.log("Captured image data URL:", dataUrl);
// Store the captured image data URL
capturedImageDataUrl = dataUrl;
// Display the captured image in the sidebar
displayCapturedImage(dataUrl);
})
.catch((error) => {
console.error('html2canvas error:', error);
});
} catch (error) {
console.error(error.message);
}
}
</code>
<code> async function mouseUpHandler(e) { if (!isSelecting) return; isSelecting = false; // Remove event listeners and overlay const overlay = document.getElementById("selectionOverlay"); overlay.removeEventListener("mousedown", mouseDownHandler); overlay.removeEventListener("mousemove", mouseMoveHandler); overlay.removeEventListener("mouseup", mouseUpHandler); document.body.removeChild(overlay); // Get the selected area coordinates const rect = selectionBox.getBoundingClientRect(); // Remove the selection boxhtm selectionBox.remove(); console.log("Selected area:", rect); try { // Wait for html2canvas to be loaded await loadHtml2Canvas(); // Ensure window.html2canvas is loaded and then use it window.html2canvas(document.body, { x: rect.left + window.scrollX, y: rect.top + window.scrollY, width: rect.width, height: rect.height, windowWidth: document.documentElement.scrollWidth, windowHeight: document.documentElement.scrollHeight, scale: window.devicePixelRatio // Adjust for high-DPI screens }) .then((canvas) => { const dataUrl = canvas.toDataURL("image/png"); console.log("Captured image data URL:", dataUrl); // Store the captured image data URL capturedImageDataUrl = dataUrl; // Display the captured image in the sidebar displayCapturedImage(dataUrl); }) .catch((error) => { console.error('html2canvas error:', error); }); } catch (error) { console.error(error.message); } } </code>
  async function mouseUpHandler(e) {
      if (!isSelecting) return;
    
      isSelecting = false;
    
      // Remove event listeners and overlay
      const overlay = document.getElementById("selectionOverlay");
      overlay.removeEventListener("mousedown", mouseDownHandler);
      overlay.removeEventListener("mousemove", mouseMoveHandler);
      overlay.removeEventListener("mouseup", mouseUpHandler);
      document.body.removeChild(overlay);
    
      // Get the selected area coordinates
      const rect = selectionBox.getBoundingClientRect();
    
      // Remove the selection boxhtm
      selectionBox.remove();
    
      console.log("Selected area:", rect);
    
      try {
        // Wait for html2canvas to be loaded
        await loadHtml2Canvas();
    
        // Ensure window.html2canvas is loaded and then use it
        window.html2canvas(document.body, {
          x: rect.left + window.scrollX,
          y: rect.top + window.scrollY,
          width: rect.width,
          height: rect.height,
          windowWidth: document.documentElement.scrollWidth,
          windowHeight: document.documentElement.scrollHeight,
          scale: window.devicePixelRatio // Adjust for high-DPI screens
        })
        .then((canvas) => {
          const dataUrl = canvas.toDataURL("image/png");
          console.log("Captured image data URL:", dataUrl);
    
          // Store the captured image data URL
          capturedImageDataUrl = dataUrl;
    
          // Display the captured image in the sidebar
          displayCapturedImage(dataUrl);
        })
        .catch((error) => {
          console.error('html2canvas error:', error);
        });
      } catch (error) {
        console.error(error.message);
      }
    }
    

And here is the loadhtml2canvas:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> function loadHtml2Canvas() {
return new Promise((resolve, reject) => {
// Check if html2canvas is already loaded
if (typeof window.html2canvas !== 'undefined') {
console.log('html2canvas is already loaded.');
resolve(); // Resolve immediately if already loaded
return;
}
// Load html2canvas dynamically
let script = document.createElement('script');
const scriptUrl = chrome.runtime.getURL('html2canvas.min.js');
console.log('Loading html2canvas from:', scriptUrl);
script.src = scriptUrl;
script.onload = function() {
console.log('html2canvas loaded dynamically.');
if (typeof window.html2canvas !== 'undefined') {
resolve(); // Resolve the promise if window.html2canvas is defined
} else {
reject(new Error('window.html2canvas is still not defined after loading.'));
}
};
script.onerror = function() {
reject(new Error('Failed to load html2canvas.'));
};
// Append the script to the document head
document.head.appendChild(script);
});
}
</code>
<code> function loadHtml2Canvas() { return new Promise((resolve, reject) => { // Check if html2canvas is already loaded if (typeof window.html2canvas !== 'undefined') { console.log('html2canvas is already loaded.'); resolve(); // Resolve immediately if already loaded return; } // Load html2canvas dynamically let script = document.createElement('script'); const scriptUrl = chrome.runtime.getURL('html2canvas.min.js'); console.log('Loading html2canvas from:', scriptUrl); script.src = scriptUrl; script.onload = function() { console.log('html2canvas loaded dynamically.'); if (typeof window.html2canvas !== 'undefined') { resolve(); // Resolve the promise if window.html2canvas is defined } else { reject(new Error('window.html2canvas is still not defined after loading.')); } }; script.onerror = function() { reject(new Error('Failed to load html2canvas.')); }; // Append the script to the document head document.head.appendChild(script); }); } </code>
  function loadHtml2Canvas() {
      return new Promise((resolve, reject) => {
        // Check if html2canvas is already loaded
        if (typeof window.html2canvas !== 'undefined') {
          console.log('html2canvas is already loaded.');
          resolve(); // Resolve immediately if already loaded
          return;
        }
    
        // Load html2canvas dynamically
        let script = document.createElement('script');
        const scriptUrl = chrome.runtime.getURL('html2canvas.min.js');
        console.log('Loading html2canvas from:', scriptUrl);
        
        script.src = scriptUrl;
    
        script.onload = function() {
          console.log('html2canvas loaded dynamically.');
          if (typeof window.html2canvas !== 'undefined') {
            resolve(); // Resolve the promise if window.html2canvas is defined
          } else {
            reject(new Error('window.html2canvas is still not defined after loading.'));
          }
        };
    
        script.onerror = function() {
          reject(new Error('Failed to load html2canvas.'));
        };
    
        // Append the script to the document head
        document.head.appendChild(script);
      });
    }

What is happening is it looks like it is correctly being loaded from the file but then it turns out to be undefined.

Here is the console.log statements:

Selected area: DOMRect {x: 0, y: 0, width: 0, height: 0, top: 0, …}

content.js:409 Loading html2canvas from: chrome-extension://geekmcfbhphgbnafmfmcmhjeaeoaikod/html2canvas.min.js

content.js:414 html2canvas loaded dynamically.

content.js:482 window.html2canvas is still not defined after loading.
mouseUpHandler @ content.js:482

Any help would be greatly appreciated.

I have tried to load this from the manifest.js like so:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["html2canvas.min.js", "content.js"]
}
],
"web_accessible_resources": [
{
"resources": ["html2canvas.min.js"],
"matches": ["<all_urls>"]
}
]
</code>
<code>"content_scripts": [ { "matches": ["<all_urls>"], "js": ["html2canvas.min.js", "content.js"] } ], "web_accessible_resources": [ { "resources": ["html2canvas.min.js"], "matches": ["<all_urls>"] } ] </code>
"content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["html2canvas.min.js", "content.js"]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["html2canvas.min.js"], 
      "matches": ["<all_urls>"]
    }
  ]

I get the same error

New contributor

Vaughn Hatfield is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật