我正在尝试在PhantomJS中创建一个简单的DOM API重载/代理示例。我打算检测页面是否尝试读取/写入其范围内的cookie。为此,我编写了以下PhantomJS 2.0脚本:
var page = require('webpage').create();
page.onInitialized = function() {
page.evaluate(function() {
(function() {
console.log('onInitialized');
var cookie_setter = document.__lookupSetter__('cookie');
var cookie_getter = document.__lookupGetter__('cookie');
Object.defineProperty(Object.getPrototypeOf(document), 'cookie', {
get: function() {
console.log('get cookie');
return cookie_getter.call(this);
},
set: function(value) {
console.log('set cookie');
return cookie_setter.apply(this, arguments);
}
});
})();
});
};
page.onLoadStarted = function() {
page.evaluate(function() {
(function() {
console.log('onLoadStarted');
var cookie_setter = document.__lookupSetter__('cookie');
var cookie_getter = document.__lookupGetter__('cookie');
Object.defineProperty(Object.getPrototypeOf(document), 'cookie', {
get: function() {
console.log('get cookie');
return cookie_getter.call(this);
},
set: function(value) {
console.log('set cookie');
return cookie_setter.apply(this, arguments);
}
});
})();
});
};
page.onConsoleMessage = function(msg) {
var log = JSON.parse(msg);
if (log.type === 'cookie') {
console.log('cookie');
}
};
page.onLoadFinished = function(status) {
console.log('page.onLoadFinished: ' + status);
if (status === 'success') {
console.log(page.content);
//phantom.exit();
}
};
page.open('http://127.0.0.1/phantom/1.html', function(status) {
/*
<html>
<body>
<script>var a = document.cookie;</script>
</body>
</html>
*/
page.evaluate(function() {
(function() {
console.log('page.open');
var cookie_setter = document.__lookupSetter__('cookie');
var cookie_getter = document.__lookupGetter__('cookie');
Object.defineProperty(Object.getPrototypeOf(document), 'cookie', {
get: function() {
console.log('get cookie');
return cookie_getter.call(this);
},
set: function(value) {
console.log('set cookie');
return cookie_setter.apply(this, arguments);
}
});
})();
});
});
但是我收到以下错误:
SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.
phantomjs://webpage.evaluate():4 in __lookupSetter__
phantomjs://webpage.evaluate():4
phantomjs://webpage.evaluate():17
phantomjs://webpage.evaluate():18
SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.
phantomjs://webpage.evaluate():4 in __lookupSetter__
phantomjs://webpage.evaluate():4
phantomjs://webpage.evaluate():17
phantomjs://webpage.evaluate():18
page.onLoadFinished: success
<html><head></head><body>
<script>var a = document.cookie;</script>
</body></html>
TypeError: Attempting to change the setter of an unconfigurable property.
phantomjs://webpage.evaluate():7 in defineProperty
phantomjs://webpage.evaluate():7
phantomjs://webpage.evaluate():17
phantomjs://webpage.evaluate():18
然而,相同的代码片段在Firefox / Chrome Dev工具以及JSFiddle中完美运行。以下是证明:https://jsfiddle.net/vmc6tz9q/3/
这甚至不适用于--web-security=false
开关。有人可以帮我调试吗?