gpt4 book ai didi

phantomjs - 将 PhantomJS 调用中的变量暴露给 injectJS

转载 作者:行者123 更新时间:2023-12-04 07:57:08 25 4
gpt4 key购买 nike

我遵循了从入门页面注入(inject) jQuery 的示例,并且效果很好。我在同一目录中有 jQuery 的本地副本,并执行类似...

if(page.injectJs('jquery.min.js')) {
page.evaluate(function(){
//Use jQuery or $
}
}

当我尝试注入(inject)自己的脚本时,没有任何功能可供我使用。假设我有一个名为 myScript.js 的脚本
function doSomething() {
// doing something...
}

然后我不能使用 doSomething 之类的...
if(page.injectJs('myScript.js')) {
console.log('myScript injected... I think');
page.evaluate(function() {
doSomething();
});
} else {
console.log('Failed to inject myScript');
}

我试过了
window.doSomething = function() {};


document.doSomething = function() {};

也没有运气,以及尝试在随后的 page.evaluate() 中使用 window.doSomething() 或 document.doSomething() 调用它们。

最佳答案

以下对我有用,也许您的应用程序逻辑的其他部分是错误的:
inject.coffee

page = require('webpage').create()

page.onConsoleMessage = (msg) -> console.log msg

page.open "http://www.phantomjs.org", (status) ->
if status is "success"
page.includeJs "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js", ->
if page.injectJs "do.js"
page.evaluate ->
title = echoAndReturnTitle('hello')
console.log title
phantom.exit()
do.coffee :

window.echoAndReturnTitle = (arg) ->
console.log "echoing '#{arg}'"
console.log $(".explanation").text()
return document.title

结果:
> phantomjs inject.coffee
echoing 'hello'

PhantomJS is a headless WebKit with JavaScript API.
It has fast and native support for various web standards:
DOM handling, CSS selector, JSON, Canvas, and SVG.
PhantomJS is created by Ariya Hidayat.

PhantomJS: Headless WebKit with JavaScript API

或者如果您更喜欢 JavaScript(它们是自动生成的,而且有点难看):

`inject.js':

// Generated by CoffeeScript 1.3.1
(function() {
var page;

page = require('webpage').create();

page.onConsoleMessage = function(msg) {
return console.log(msg);
};

page.open("http://www.phantomjs.org", function(status) {
if (status === "success") {
return page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js", function() {
if (page.injectJs("do.js")) {
page.evaluate(function() {
var title;
title = echoAndReturnTitle('hello');
return console.log(title);
});
return phantom.exit();
}
});
}
});

}).call(this);
do.js :

// Generated by CoffeeScript 1.3.1
(function() {

window.echoAndReturnTitle = function(arg) {
console.log("echoing '" + arg + "'");
console.log($(".explanation").text());
return document.title;
};

}).call(this);

关于phantomjs - 将 PhantomJS 调用中的变量暴露给 injectJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10156190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com