Reputation: 5409
For some reason this script isn't working:
element.text = "function TestClick() { $('" + testElement + "').click() }";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("TestClick");
The webBrowser2
control is on http://google.com, and the variable testElement
equals .gbts
. If I run the script $("gbts").click();
on developer tools in Chrome on Google it works fine, but when I try to invoke the script into a WebBrowser control I get the error
"$ is undefined"
and nothing happens. What am I doing wrong?
Upvotes: 0
Views: 2064
Reputation: 11438
Nir Azuelos provides part of the answer. Indeed, for this code to work when you insert it, you need jQuery or something else that would implement this API. (Zepto would probably work)
The reason it works in the Chrome console is that Chrome defines $
and $$
(among others) in the console itself, as a convenience to developers.
In the console, if you type $
and you see function $() { [Command Line API] }
as output, then it means that $
was not defined on the page itself. Thus it won't be available to any scripts within the page.
Note that $ function provided in the Chrome console works wholly differently than the $ function provided by jQuery. In Chrome console, $ (by default) is mapped to behavior similar to document.querySelector
. See https://developers.google.com/chrome-developer-tools/docs/console for documentation.
Also, if you want to inject only simple scripts, you may be able to avoid using jQuery altogether. In principle, your code would work if you'd either replace $
with document.querySelector
, or assign document.QuerySelector
to $
before attempting to call $
.
"function TestClick() { document.querySelector('" + testElement + "').click() }";
There are big differences between native DOM API and jQuery, so you should decide which one you want to use.
Upvotes: 0
Reputation: 1171
$
is probably a reference for a jQuery instance. You need to include jQuery into your web page in order for this to work.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Upvotes: 1