如何解决在 cdt Chrome DevTools Java Client (com.github.kklisura.cdt) 中运行 Javascript
有没有办法在 cdt 中渲染之前运行 javascript?
page.addScriptToEvaluateOnLoad("(function() { alert("testing")})()") page.addScriptToEvaluateOnLoad 在页面加载时执行,而不是在 dom 完成后执行
解决方法
需要利用com.github.kklisura.cdt.protocol.commands.Runtime 在下面的示例方法中,我将从网页中删除粘性固定内容,然后将其转换为 pdf
private void convertToPdf(Long masterSourceId,String url,String outputFilePath,Double screenshotLoadTime) {
ExecutorService mainExecutor = Executors.newSingleThreadExecutor();
try (ChromeLauncher launcher = new ChromeLauncher()) {
Callable<Boolean> pdfTask = () -> {
Map<String,Object> additionalChromeArguments = new HashMap<>();
additionalChromeArguments.put("no-sandbox",true);
ChromeArguments chromeArguments = ChromeArguments.builder().noFirstRun().noDefaultBrowserCheck()
.disableBackgroundNetworking().disableBackgroundTimerThrottling()
.disableClientSidePhishingDetection().disableDefaultApps().disableExtensions()
.disableHangMonitor().disablePopupBlocking().disablePromptOnRepost().disableSync()
.disableTranslate().metricsRecordingOnly().safebrowsingDisableAutoUpdate().headless(true)
.disableGpu(true).hideScrollbars(true).muteAudio(true)
.additionalArguments(additionalChromeArguments).build();
additionalChromeArguments.put("no-sandbox",true);
ChromeService chromeService = launcher.launch(chromeArguments);
ChromeTab tab = chromeService.createTab();
ChromeDevToolsService devToolsService = chromeService.createDevToolsService(tab);
devToolsService.getEmulation().setScriptExecutionDisabled(false);
devToolsService.getEmulation().setDocumentCookieDisabled(true);
Page page = devToolsService.getPage();
page.enable();
page.navigate(url);
page.onLoadEventFired(loadEventFired -> {
/*
* This below script will make sure that any floating,sticky cookie popups in
* the web Page will not cover the content when the pdf is being taken from the
* HTML THe script will return the dom elements after javascript has modified
* the values
*/
Runtime runtime = devToolsService.getRuntime();
runtime.evaluate(
"(function(){x=document.querySelectorAll('*');for(i=0;i<x.length;i++){elementStyle=getComputedStyle(x[i]);if(elementStyle.position=='fixed'||elementStyle.position=='sticky'){x[i].remove();}}}())");
runtime.evaluate(
"(function() {l = document.getElementsByTagName(\"a\"); for (var i =0; i<l.length; i++) {l[i].href = \"\"; } }())");
dump(masterSourceId,outputFilePath,page.printToPDF(false,false,true,null,11.7,16.5,null).getData());
devToolsService.close();
});
devToolsService.waitUntilClosed();
chromeService.closeTab(tab);
return true;
};
Future<Boolean> exeFuture = mainExecutor.submit(pdfTask);
exeFuture.get(10,TimeUnit.MINUTES);
} catch (Exception ex) {
log.error(masterSourceId + " : ERROR OCCURED IN HTML TO PDF CHROME CONVERTER : " + ex.getMessage());
} finally {
mainExecutor.shutdownNow();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。