brenden / node-webshot

Easy website screenshots in Node.js
2.12k stars 286 forks source link

Trouble getting serialized context variables running in onLoadFinished #195

Open minessis opened 7 years ago

minessis commented 7 years ago

Having trouble getting serialized context variables running in my onLoadFinished phantom page callback.. see: webshot#phantom-callbacks From the docs:

Arbitrary scripts can be run on the page before it gets rendered by using any of Phantom's page callbacks

Note that the script will be serialized and then passed to Phantom as text, so all variable scope information will be lost. However, variables from the caller can be passed into the script as follows:

var options = {
  onLoadFinished: {
    fn: function() {
      var links = document.getElementsByTagName('a');

      for (var i=0; i<links.length; i++) {
        var link = links[i];
        link.innerHTML = this.foo;
      } 
    }
  , context: {foo: 'My custom text'}
  }
};

I'm seeing:

// Works...
getStreamedWebshot(tempalte, myId) {
  return webshot(`${template}.html`, {
    siteType: 'file',
    takeShotOnCallback: true,
    onLoadFinished: function() {
        var chart = document.getElementsById('chart')
        chart.innerHTML = 'Test chart data'
        window.callPhantom('takeShot')
    }
  }
}
// Does not work...
getStreamedWebshot(template, myId, myData) {
  return webshot(template, {
    siteType: 'file',
    takeShotOnCallback: true,
    onLoadFinished: {
      fn: function() {
        var chart = document.getElementsById(this.id)
        chart.innerHTML = this.data
        window.callPhantom('takeShot')
      },
      context: { id: myId, data: myData }
    }
  }
}

Usage:

const streamToS3 = (stream, { Bucket, Key, ContentEncoding }) => {
  new Promise((resolve, reject) => {
    let upload = s3Stream.upload({ Bucket, Key, ContentEncoding })
    upload.on('uploaded', resolve).on('error', reject)
    stream.pipe(upload).on('error', reject)
  })
}

try {
  let pngStream = await getStreamedWebshot('./default.html', 2, 'test')
  let details = await streamToS3(pngStream, { Bucket, Key, 'image/png' })
  console.log('> details', details)
} catch(err) {
  console.log('> error', err)
}

Outcome: The one that works, works great! The one that doesn't work just hangs... doesn't throw an error, just hangs...

Please advise!

titandino commented 6 years ago

Anyone find a solution for this yet? I did enable error logging and it seems to be PhantomJS not finding a file or something.