问题
How can I add a html2canvas to a given webpage, execute it, and then read its results with Watir?
require 'watir'
b = Watir::Browser.new :firefox
b.goto "google.com"
path = "/path/to/html2canvas.js" # v. 0.5.0-alpha1
h2c_payload = File.read(path)
b.execute_script h2c_payload
h2c_activator = %<
function genScreenshot () {
var canvasImgContentDecoded;
html2canvas(document.body, {
onrendered: function (canvas) {
window.canvasImgContentDecoded = canvas.toDataURL("image/png");
}});
};
genScreenshot();
>.gsub(/\s+/, ' ').strip
b.execute_script h2c_activator
b.execute_script "return window.canvasImgContentDecoded"
=> nil
Executing the same JavaScript in the console results in the variable (eventually) being set and then returned when called. What is different about execute_script
?
回答1:
The problem is that canvasImgContentDecoded is being checked before the canvas finishes being rendered. Not being a JavaScript programmer, I find it easier to do the waiting in Ruby/Watir instead:
result = nil
b.wait_until { result = b.execute_script "return window.canvasImgContentDecoded;" }
p result
#=> "data:image/png;base64,iVBORw0KGgoA..."
The above will only fix the problem when using Chrome.
Firefox seems to have other limitation and/or restrictions that prevent the original code from working. The following worked in Firefox and in Chrome. Note that this might require the more current version of html2canvas:
require 'watir'
b = Watir::Browser.new :firefox
b.goto("google.com")
# Load html2canvas - currently v1.0.0-alpha.9
h2c_payload = %<
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://html2canvas.hertzen.com/dist/html2canvas.js';
document.head.appendChild(script);
>.gsub(/\s+/, ' ').strip
b.execute_script(h2c_payload)
# Wait for html2canvas to load
b.wait_while { b.execute_script("return typeof html2canvas === 'undefined'") }
# Generate the canvas
h2c_activator = 'html2canvas(document.body).then(canvas => {window.canvasImgContentDecoded = canvas.toDataURL("image/png");});'
b.execute_script h2c_activator
# Wait for canvas to be created
result = nil
b.wait_until { result = b.execute_script "return window.canvasImgContentDecoded;" }
p result
#=> "data:image/png;base64,iVBORw0KGgoA..."
来源:https://stackoverflow.com/questions/48208920/how-to-add-and-execute-html2canvas-on-a-webpage-with-watir