Any one has a idea on how to invoke a javascript function from puppeteer which is not inline but in an external .js file. If its inline within the html->head->script tag it works but not if the script tag points to an external .js file
Sample HTML File
<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>
Sample Javascript file
/*----------------------------------------------------*/
/* External Javascript File */
/*----------------------------------------------------*/
function fileFunction() {
window.location.replace('https://www.geeksforgeeks.org');
}
Puppeteer code sample
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();