Using the HTML <noscript>
Element
The purpose of the <noscript>
tag is to provide an alternative content for users who have disabled scripts in their browser or are using a browser that doesn't support scripting. The <noscript>
element can be included within both the <head>
and <body>
sections. When placed inside the <head>
section, the <noscript>
should only contain <link>
, <style>
, or <meta>
elements. The content enclosed by the <noscript>
tags will be displayed if scripts are not supported or disabled in the user's browser.
Here is a code example:
WebDriver driver = new HtmlUnitDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.setJavascriptEnabled(true);
driver.get("https://stackoverflow.com/questions/7926246/why-doesnt-htmlunitdriver-execute-javascript");
System.out.println(driver.getPageSource());
When running this code snippet, an error may occur at the line:
driver.setJavascriptEnabled(true);
To resolve this, there are two possible solutions available:
Option 1: Typecast the driver instance before invoking setJavascriptEnabled(true)
:
((HtmlUnitDriver) driver).setJavascriptEnabled(true);
Option 2: Pass the parameter true during initialization to enable javascript support:
WebDriver driver = new HtmlUnitDriver(true);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://stackoverflow.com/questions/7926246/why-doesnt-htmlunitdriver-execute-javascript");
System.out.println(driver.getPageSource());
driver.quit();
Both approaches yield identical results which include:
<?xml version="1.0" encoding="UTF-8"?>
<html itemscope="" itemtype="http://schema.org/QAPage" class="html__responsive">
<head>
<title>
java - Why doesn't HtmlUnitDriver execute JavaScript? - Stack Overflow
</title>
...
[Additional metadata and script references]
</head>
<body class="question-page unified-theme">
<noscript id="noscript-css">
<style>body,.top-bar{margin-top:1.9em}</style>
</noscript>
<div id="notify-container">
</div>
... [Other website content] ...
</script> <!-- Closing script tag -->
</body>
</html>