Example:
<script type="text/javascript">
function test() {
console.log("Hello world");
}
</script>
How would I call test()
?
Edit: I didn't explain this correctly.
I am using the request module of node.js to load an external html file that contains javascript functions:
request.get(options, function (error, response, body) {
if (error && response.statusCode !== 200) {
}
else {
jsdom.env({
html: body,
scripts: ["../jquery-1.6.4.min.js"]
}, function (err, window) {
var $ = window.jQuery;
I'm just looking for the syntax to call a function in 'body'.
Just call it like any other function on your page, jQuery is a framework and is not needed for running a JS function.
So the problem here is that by default, jsdom.env
does not execute javascript found while processing markup.
You'll need to turn these features on:
jsdom.env({
// ...
features : {
FetchExternalResources : ['script'],
ProcessExternalResources : ['script']
}
});
FetchExternalResources
controls whether or not jsdom should even bother reaching across the network/disk to collect the bytes of a resource
ProcessExternalResources
controls whether or fetched scripts are executed
Note these names were chosen to encompass other resources types (read: images, css, etc..) which will be added in the future. The idea here is to provide sane defaults, but have many turnable knobs that affect the behavior of jsdom.
hmmm... probably I'd go with
test();
But that's not jquery, it's plain old javascript.
Try this:
...
function (err, window) {
var $ = window.jQuery;
window.test();
...
You could also try:
<script type="text/javascript" id="myscript">
function test() {
console.log("Hello world");
}
</script>
And then:
function (err, window) {
var $ = window.jQuery;
(1,window.eval)( $("#myscript").html() );
window.test();
来源:https://stackoverflow.com/questions/8345054/how-to-call-a-javascript-function-defined-in-a-script-tag