如何使用Watir在网页上添加和执行html2canvas [英] How to add and execute html2canvas on a webpage with Watir
问题描述
如何将html2canvas添加到给定的网页,执行它,然后使用Watir读取其结果?
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
在控制台中执行相同的JavaScript会导致变量(最终)被设置,然后在调用时返回. execute_script
有什么区别?
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
?
推荐答案
问题是在渲染画布之前要检查canvasImgContentDecoded.不是JavaScript程序员,我发现在Ruby/Watir中更容易进行等待:
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..."
以上内容只能在使用Chrome时解决该问题.
The above will only fix the problem when using Chrome.
Firefox似乎还有其他限制和/或限制,导致原始代码无法正常工作.以下内容适用于Firefox和Chrome.请注意,这可能需要最新版本的html2canvas:
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..."
这篇关于如何使用Watir在网页上添加和执行html2canvas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!