I have a Selenium Java library that includes a JavaScript "glue" library that enables JavaScript functions to throw serialized Java exceptions. This enables much more natural handling of exceptional conditions without a lot of boilerplate.
Prior to executing a script that may want to throw an exception, I inject this library into the target page in a closure via executeScript
. Upon return, the functions defined in the closure persist on the page, available for scripts that execute afterward to use for throwing exceptions.
This technique works as expected on HtmlUnit, Chrome, and Edge. However, the enclosed functions don't persist when I use this technique on Firefox. If I paste the closure into the multi-line editor in Developer Tools, the functions are retained, but this isn't a strategy I can use in Selenium Java automation.
Is there a different method I can use to add functions to a web page on-the-fly? Is there a Firefox setting that might allow the technique I'm using to work as expected?
The source for the script I'm using now can be found here: https://github.com/sbabcoc/Selenium-Foundation/blob/master/src/main/resources/javaGlueLib.js As indicated in the comments, the structure and "namespace" functionality of the closure was obtained from here: https://github.com/jweir/namespace/blob/master/namespace.js
CodePudding user response:
This maybe a limitation of Firefox itself. But I am only guessing.
Have you tried a Man in the Middle proxy? such as https://mitmproxy.org
You will need to be in an environment where your test browsers can trust the MITM certificate. Then you can configure the MITM server to inject whatever you want into the requests.
The advantage of a MITM is will be browser agnostic.
Another option might be to use GreaseMonkey for Firefox. https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/
CodePudding user response:
I found my answer. I always knew that my original implementation was drawing outside the lines, and Firefox won't let me get away with that.
The solution is to create a script
element, set the [textContent] of this element to my original script source, and attach this new script
node to the head
element of my target page.
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.textContent = arguments[0];
head.appendChild(script);