HtmlUnit / htmlunit

HtmlUnit is a "GUI-Less browser for Java programs".
https://www.htmlunit.org
Apache License 2.0
875 stars 172 forks source link

Accessing global variables in separate scripts #874

Open kincsescsaba opened 1 month ago

kincsescsaba commented 1 month ago

I have an HTML loading multiple scripts:

<html>
  <head>
    <script src="scriptDeclaringAGlobalVar.js"></script>
    <script src="scriptReadingAGlobalVar.js"></script>
...

scriptDeclaringAGlobalVar.js:

var aGlobalVar = "hello"

scriptReadingAGlobalVar.js:

$(document).ready(function(){
  console.log(aGlobalVar);
});

Though the global variable is declared in the first script, and even $(document).ready was used, it can't be reached, I get errors like this in HtmlUnit:

jQuery.Deferred exception: "aGlobalVar" is not defined. @http://localhost:8080/scriptReadingAGlolbalVar.js:2
@https://code.jquery.com/jquery-3.7.0.js:3479
@https://code.jquery.com/jquery-3.7.0.js:3547

The same works fine in browsers.

rbri commented 1 month ago

Will have a look and maybe add a test case but if fear this works in general and is related to the jQuery initialization

kincsescsaba commented 1 month ago

The above example is simplified. I checked putting a $(document).ready block also in scriptDeclaringAGlobalVar.js, which successfully read aGlobalVar. That's why I think the issue is related to handling scopes of multiple script includes.

rbri commented 4 days ago

@kincsescsaba Have just added a small test implementation to the test suite.

Can you please have a look at the test and check if i got your problem right.