Reputation: 77
I am trying to execute a javascript file through webdriver in C#. The following is what i have so far:
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
(string)js.ExecuteScript("var s = window.document.createElement(\'script\'); s.src = \'E:\\workspace\\test\\jsPopup.js\'; window.document.head.appendChild(s); ");
js.ExecuteScript("return ourFunction");
The content of jsfile.js are
document.ourFunction = function(){ tabUrl = window.location.href;
imagesPath = chrome.extension.getURL("images");
var optionsPopupPath = chrome.extension.getURL("options.html");
}
However when i execute
js.ExecuteScript("return ourFunction");
It throws an exception of ourFunction not found. What i want to do is run a complete javascript file through js injection or any other method that would let me access the data generated by the js file. Any help ?
Upvotes: 1
Views: 5497
Reputation: 5113
There are three problems here:
ourFunction()
, not ourFunction
, otherwise you'll get an error along the lines of Uncaught ReferenceError: ourFunction is not defined(…)
ourFunction
is added to document
not the global scope, so you'd need document.ourFunction()
, otherwise you'll get the same error.undefined
. If you try to return the 'value' of it, you'll get something like Uncaught SyntaxError: Illegal return statement(…)
in the browser, or probably null
back in your code.You can test all of this from your browser console without needing to fire up WebDriver.
If you changed the method to:
document.ourFunction = function(){ tabUrl = window.location.href;
imagesPath = chrome.extension.getURL("images");
var optionsPopupPath = chrome.extension.getURL("options.html");
return optionsPopupPath; // return here!
}
Then js.ExecuteScript("return document.ourFunction()");
ought to work.
Update:
(You could maybe try: js.ExecuteScript("return document.ourFunction();");
(added semicolon) but that shouldn't make a difference.)
I'd suggest (in addition to adding the return
statement) temporarily commenting out the chrome.extension
lines in case these are throwing errors and causing the function to fail to be created. I think that's far the most likely source of failure.
Having done that, this works fine for me in Firefox and Chrome without any explicit or implicit waits at all.
Upvotes: 1