I am writing an app in node.js, using mongoose and express. I want to pass an async function that opens a browser window using puppeteer to an ejs page, and run that function with a button click. At the moment, when the ejs page is opened, the function runs immediately and the browser window is opened. I want the function not to run until a button is pressed.
My code looks like this:
browserModule.js
const puppeteer = require('puppeteer');
export.modules = async function startBrowser {
let browser;
try {
console.log("Opening the browser......");
browser = await puppeteer.launch({
headless: false,
args: [
"--disable-setuid-sandbox",
],
'ignoreHTTPSErrors': true
});
} catch (err) {
console.log("Could not create a browser instance => : ", err);
}
}
pageController.js
const browserModule = require('../browserModule');
module.exports.renderNewForm = async (req, res) => {
res.render('/new', browserModule.startBrowser);
}
new.ejs
<button class="btn btn-info" onclick=openBrowser>Open Book Site</button>
<!-- NOTE: This code does nothing, the openBrowser function runs immediately
and the new browser window is opened. Clicking on the button has no effect. -->
I have looked at some similar questions that suggest putting the function code in a script in the ejs file (which I would like to avoid), or creating an event handler (I couldn't figure out how to apply that idea to my code).
Thanks
You can achieve something like that by making reference to the function rather than calling it.
Change const openBrowser = browserModule.startBrowser();
to const openBrowser = browserModule.startBrowser;
I was incorrectly trying to use a web browser app inside an ordering app by calling a function from the web browser app from a view for the ordering app. Marc was correct in saying that couldn't be done.
I had two options: separate out the 2 apps and create a web browser api that I could use with the ordering app, or integrate the web browser app fully into the ordering app.
I chose the later, and, using the MVC pattern, have created separate model and routes files for the browser that live along-side those for the ordering app.