需求
出于调试需要,将二进制的数据从文件中读取出来,然后再传到页面中,然后在页面中单步调试。
具体如下:
- 从文件中读取byte[]
- 将byte[]转为List
- 将List
传到页面中,作为array类型 - 将js中的array类型,再转为ArrayBuffer,以供实际调试使用
实现
```javascript import com.google.common.primitives.Ints; import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserType; import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils;
import java.io.File; import java.io.IOException; import java.util.List;
/**
用于测试playwright向页面传递字节数组 / @Slf4j public class Test1 { /*
- 将byte[] 转为 List
- @param bytes
@return */ public static List
convertToIntegerList(byte[] bytes){ //先将byte[] 转为 int[] int[] intArray = new int[bytes.length]; for (int i = 0; i < bytes.length; intArray[i] = bytes[i++]); //然后再将 int[] 转为 List
List finalInts = Ints.asList(intArray); return finalInts; } /**
- 将文件中的二进制数据,传递到页面,保存为全局对象(Uint8Array)
- 其中对象名称就是文件的名称
- @param page
@param file */ public static void copyFileDataToPage(Page page, File file) throws IOException { String name = file.getName(); byte[] bytes = FileUtils.readFileToByteArray(file); String jsCode = String.format(“array => window.%s=new Uint8Array(array)”, name); page.evaluate(jsCode, convertToIntegerList(bytes)); }
public void capture(String captureUrl) {
log.debug(“start to test playwright demo”); try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setDevtools(true).setSlowMo(50));
Page page = browser.newPage();
page.navigate(captureUrl);
//等待页面加载完成
page.waitForLoadState();
//将文件中的二进制数据,拷贝到页面
copyFileDataToPage(page,new File("C:\\Users\\wchi\\Desktop\\data\\MyData0"));
page.waitForTimeout(3000 * 1000);
log.debug("over");
} catch (IOException e) {
e.printStackTrace();
} }
- 将byte[] 转为 List
public static void main(String[] args) {
Test1 demo = new Test1();
demo.capture("https://www.baidu.com");
}
}
<a name="Bx6os"></a>
# 效果
如下所示, js中看到的数据,和文件中的数据是一致的。<br />
<a name="hFjqj"></a>
# 其它
本来准备是通过chrome console中的js代码来实现加载本地数据的,结果一直失败。
```javascript
let download=function download() {
let url = 'file://C:/Users/wchi/Desktop/data/MyData0';
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // 也可以使用POST方式,根据接口
xhr.responseType = "blob"; // 返回类型blob
xhr.onload = function () {
// 请求完成
if (this.status === 200) {
let blob = this.response;
console.log("成功下载到数据");
}
};
// 发送ajax请求
xhr.send()
}
download()
即使设置了chrome的 --allow-file-access-from-file --disable-web-security
这两个选项也没用。
估计是最新的安全策略限制。