如何使用Watir在网页上添加和执行html2canvas

如何将html2canvas添加到给定的网页,执行它,然后使用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 = %.gsub(/\s+/, ' ').strip b.execute_script h2c_activator b.execute_script "return window.canvasImgContentDecoded" => nil 

在控制台中执行相同的JavaScript会导致变量(最终)被设置,然后在调用时返回。 execute_script什么不同?

问题是canvas在canvas完成渲染之前正在检查canvasImgContentDecoded。 不是JavaScript程序员,我发现在Ruby / Watir中等待更容易:

 result = nil b.wait_until { result = b.execute_script "return window.canvasImgContentDecoded;" } p result #=> "data:image/png;base64,iVBORw0KGgoA..." 

以上内容仅解决了使用Chrome时遇到的问题。

Firefox似乎有其他限制和/或限制,阻止原始代码工作。 以下内容适用于Firefox和Chrome。 请注意,这可能需要更新版本的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..."