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

时间:2018-01-11 14:05:28

标签: javascript ruby selenium-webdriver watir

如何将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 = %<
  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

1 个答案:

答案 0 :(得分:1)

问题是在画布完成渲染之前正在检查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..."