【发布时间】:2021-05-19 04:15:24
【问题描述】:
任何人都知道如何从 puppeteer 中调用 javascript 函数,该函数不是内联的,而是在 external .js 文件中的。如果它在 html->head->script 标记中内联,则它可以工作,但如果脚本标记指向外部 .js 文件,则不会
示例 HTML 文件
<html>
<head>
<script type="text/javascript">
function inlineFunction() {
window.location.replace('https://www.geeksforgeeks.org');
}
</script>
<script src="script.js" type="text/javascript">
</script>
</head>
<body>
<p>Hello</p>
<p>this is an online html</p>
<p>Link with tag a <a href="https://www.geeksforgeeks.org" name="arivalink">Href Link</a></p>
<p>Link with inline java script - <a href="#" onClick='inlineFunction();'>Inline JS link</a></p><!-- Works -->
<p>Link with external JS file w/o tagname - <a href="#" onClick='fileFunction();'>Ext JS Link</a></p><!-- Does not work -->
<p>Link with external JS file w/ tagname - <a href="#" onClick='fileFunction();' name="geeksLink">Ext JS Link</a></p><!-- Does not work -->
</body>
</html>
示例 Javascript 文件
/*----------------------------------------------------*/
/* External Javascript File */
/*----------------------------------------------------*/
function fileFunction() {
window.location.replace('https://www.geeksforgeeks.org');
}
Puppeteer 代码示例
const puppeteer = require('puppeteer');
async function start() {
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
//Change the path of "url" to your local path for the html file
const url = 'file:///Users/sam.gajjar/SG/Projects/headless-chrome/sample.html';
var link = '[name="link"]';
console.log("Main URL Called");
await page.goto(url);
console.log("Link via HTML tag A called");
await page.click(link);
await page.waitForTimeout(5000) // Wait 5 seconds
.then(() => page.goBack());
console.log("Callng inline JS Function");
await page.evaluate(() => inlineFunction());
await page.waitForTimeout(5000) // Wait 5 seconds
.then(() => page.goBack());
console.log("Callng extjs file Function");
await page.evaluate(() => fileFunction());
await page.waitForTimeout(5000) // Wait 5 seconds
.then(() => page.goBack());
// console.log("Callng extjs file Function w/tag name");
// const element = await page.$$('[a href="#"]');
// await page.waitForTimeout(5000)
// .then(() => page.goBack());
}
start();
【问题讨论】:
-
@ggorlen - 添加了 puppeteer 代码,其中调用 HTML A 标记和调用内联 JS 函数有效,但外部 JS 中的相同函数不起作用。 puppeteer 代码将使用 HTML A 调用 Link 然后返回并调用内联 JS 函数,然后返回并在失败的地方调用 extJS 函数。
标签: javascript puppeteer