0

I'm currently building a Google Chrome extension that takes multiple screenshots from different pages and posts them on an endpoint. The problem I'm having is that the timing is off. What I mean is that the screenshot gets taken way too early before the page even stops loading. Second, I'm only receiving the second screenshot from link type WE(not the first one from type PA) as if the action is too fast and just skips over PA. I'm not really good with JS, if someone have pointers on how to make this code better I'm all ears. Thank you.

background.js

var id = 100;
var currentObject;
var myTimer;

function wait()
   {setTimeout(wait, 1000);}

chrome.browserAction.onClicked.addListener(
function fireTimer() {
    localStorage["allLocations"] = JSON.stringify([{
      'type': 'PA',
      'url': 'https://app.powerbi.com/groups/me/reports/ReportSection2?chromeless=true'
    },
    {
      'type': 'WE',
      'url': 'https://app.powerbi.com/groups/me/reports/ReportSection?chromeless=true'
    }]);
    myTimer = setInterval(fireScreenshots, 1*60*1000);
});

function fireScreenshots(){
  var allLocations = JSON.parse(localStorage["allLocations"]);
  allLocations.forEach( function (arrayItem)
  {
      if (arrayItem.type != undefined && arrayItem.url != undefined){
        retrieveWebPage(arrayItem)
      }
  });
}

function retrieveWebPage(data){
  currentObject = data;
  chrome.tabs.update({
       url: currentObject.url
  });
  chrome.tabs.onUpdated.addListener(function updatedListener(tabId , info) {
  chrome.tabs.onUpdated.removeListener(updatedListener);
  if (info.status == 'complete' && currentObject != undefined) {
    chrome.tabs.captureVisibleTab(null, {format: "jpeg", quality: 100}, function(screenshotUrl) {
      var xhr = new XMLHttpRequest() , formData = new FormData();
      formData.append("image", screenshotUrl);
      formData.append("dashboard_type", currentObject.type);
      xhr.open("POST", "http://intranet/api/powerbi/screenshots_upload/");
      xhr.send(formData);
    });
  }
});
}
Miguel Rosales
  • 769
  • 4
  • 13
  • 29

1 Answers1

1

It's strange that the verification info.status == 'complete' isn't enough to know that the page is loaded.

A 1 second timeout could be a temporary solution to your problem. It could be that some scripts in the webpages you are loading are doing work to update/display the web page even after the DOM has finished loading (especially in SPAs-type applications).

setTimeout(function() {
chrome.tabs.captureVisibleTab(null, {format: "jpeg", quality: 100}, function(screenshotUrl) {
      var xhr = new XMLHttpRequest() , formData = new FormData();
      formData.append("image", screenshotUrl);
      formData.append("dashboard_type", currentObject.type);
      xhr.open("POST", "http://intranet/api/powerbi/screenshots_upload/");
      xhr.send(formData);
    });
}, 1000);
Adam Cherti
  • 962
  • 1
  • 8
  • 21