automating browser with phantom.js - javascript

I am trying to automate the browser using phantomjs. I load a page, supply the login credentials and then want to click on the submit button. As the first step I loaded a page, modified the form values and piped the output to a .html file to see if that works. Here is my code:
var page = require('webpage').create();
var fs = require('fs');
page.onConsoleMessage = function(msg) {
fs.write("/home/phantom/output.html", msg, 'w');
};
page.settings.userAgent = 'SpecialAgent';
//page.open('http://google.com', function(status) {
page.open('https://somewebsitehavingaform.com', function(status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function() {
document.getElementsByName('id').value="id";
document.getElementsByName('name').value="name";
document.getElementsByName('password').value="password";
console.log(document.body.innerHTML);
});
}
phantom.exit();
});
When i open the output.html, it shows me the form but its empty. I expected id,name and password to be pre-filled. Where i am going wrong here?

First of all, getElementsByName will return an array. In order to set the value of the first input found with that name, you'd need to choose a specific element in it, i.e. the first:
getElementsByName('foo')[0].value = 'bar'
Then, if you change the assignment to use setAttribute it seems to work correctly:
var ua = page.evaluate(function() {
document.getElementsByName('id')[0].setAttribute("value", "id");
document.getElementsByName('name')[0].setAttribute("value", "name");
document.getElementsByName('password')[0].setAttribute("value", "password");
console.log(document.body.innerHTML);
});
According to the Mozilla docs,
Using setAttribute() to modify certain attributes, most notably value
in XUL, works inconsistently, as the attribute specifies the default
value. To access or modify the current values, you should use the
properties. For example, use elt.value instead of
elt.setAttribute('value', val).
Though since you're just writing out the resulting HTML to file, I don't think it should cause you a problem in this instance.
Not sure if Phantom JS is now using the QJSEngine internally, but notice this open ticket on their backlog that might be related to the issue you're getting with dot notation:
QJSEngine is a simple wrapper around V8, mainly for use with QtQml.
Using QJSEngine for the PhantomJS main context might prove to be more
malleable/customizable than the current implementation.
Problems:
…
Automatic property creation when using dot notation does not work with QObjects added to the QJSEngine
(This suggests that QJSEngine isn't the current implementation in use, but was raised 9 months ago, so not sure if it's been introduced since then, so thought it was worth flagging)

Related

JavaScript limits to prototype-based inheritance?

This is not a question about how to extend JS natives and I am well aware of the "dangers" involved with such activity. I am only trying to get a deeper understanding of how JavaScript works. Why is it that if I write the following:
CSSStyleSheet.prototype.sayHi = function() {
console.log('CSSStyleSheet says hi!');
};
var test = new CSSStyleSheet;
test.sayHi(); // Console output: CSSStyleSheet says hi!
I get the expected output from the sayHi function. But if I then query a style element and produce a CSSStyleSheet object
from it via the sheet property, the sayHi function is not defined:
var styleElm = document.querySelector('style'),
sheet = styleElm.sheet;
console.log('sheet', sheet) // Console output: sheet CSSStyleSheet {ownerRule: null,...
sheet.sayHi(); // Console output: Uncaught TypeError: sheet.sayHi is not a function
What is the reason for this? What would I have to do to make the sayHi function available to a CSSStyleSheet object produced via the sheet property - is it even possible?
The test was run in Chrome.
EDIT:
The reason I am looking into this is because I am trying to weigh my options when it comes to simplifying existing code. I have made an API to manipulate internal styles of a document loaded in an iFrame. It works as intended, but I would like to simplify the code if possible. It builds on the CSSOM API, which allows access to individual CSS style rules via numerical indexes. Having numerical indexes as the only way to access CSS rules seems quite rudimentary since you would never request a particular index unless you knew what rule the index pointed to. That is, you would always need to have info about the selector text. But it is the only way that makes sense in a broad context given the cascading nature of CSS (where you can have the same selector text as many times as you like).
However, my API keeps things in order so that every selector text is unique. Therefore, it makes sense to index the rules so that the main way of accessing them is via their selector text and my API does just that. However, things can quickly get less elegant when more than one level of rules are in play, i.e. if you have a number of media query rules containing their own index of CSS rules.
So I am just wondering if I can do anything to simplify the code and I must admit that were it not for the in this thread illustrated problems with hosted objects, i might have considered extending the CSSStyleSheet object.
Are there any other approaches, I might consider?
As it turned out, the issue is not about hosted object prototype limitations: while there are truly some, your particular example should work fine. The real problem is attempting to access this augmented prototype within iframe, which has its own global object. While there's a link between iframe's window and its host window, it's not used in the name resolving mechanism (few exceptions aside).
So the real challenge is to access host properties from within iframe. Now there are two ways of doing this: the easy one and the usual one.
The easy one is based on assumption that host and iframe share the same domain. With CORS concerns out of the way, you can connect those through parent property, as...
When a window is loaded in an <iframe>, <object>, or <frame>, its
parent is the window with the element embedding the window.
For example:
// host.html
<script>
CSSStyleSheet.prototype.sayHi = (space) => {
console.log(`CSSStyleSheet says hi! from ${space}`);
};
</script>
<iframe sandbox="allow-same-origin allow-scripts" src="iframe.html" />
// iframe.html
<button>Say Hi!</button>
<script>
Object.setPrototypeOf(CSSStyleSheet.prototype, parent.CSSStyleSheet.prototype);
document.querySelector('button').onclick = () => {
new CSSStyleSheet().sayHi('inner space');
};
</script>
... and it should work. Here, Object.setPrototypeOf() is used to connect CSSStyleSheet.prototype of a parent (host) window to iframe's own CSSStyleSheet.prototype. Yes, garbage collector suddenly has got more work to do, but technically this should be considered a problem of browser writers, not yours.
Don't forget to test this on proper HTTP(S) Server locally, as file:/// based iframes are not really cors-friendly.
If your iframe is from another castle domain, things get way more interesting. In particular, any attempt to access parent directly is just blocked with that nasty Uncaught DOMException: Blocked a frame with origin "blah-blah" message, so no free cookies.
Technically, however, there's still a way to bridge that gap. What follows is some food for thought, showing that bridge in action:
console.clear(); // check the browser console; iframe's one won't be visible here
CSSStyleSheet.prototype.sayHi = (space) => {
console.log(`CSSStyleSheet says hi! from ${space}`);
};
document.querySelector('button').onclick = () => {
new CSSStyleSheet().sayHi('outer space');
};
const html = `<button>Say Inner Hi!</button><br />
<script>
parent.postMessage('PING', '*'); // HANDSHAKE
document.querySelector('button').onclick = () => {
new CSSStyleSheet().sayHi('inner space');
};
addEventListener('message', (event) => {
const { data } = event;
if (data === null) {
delete CSSStyleSheet.prototype.sayHi;
}
else {
CSSStyleSheet.prototype.sayHi = eval(data);
}
}, false);
<` + `/script>`;
const iframe = document.createElement('iframe');
const blob = new Blob([html], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
document.body.appendChild(iframe);
let iframeWindow = null;
addEventListener('message', event => {
if (event.origin !== "null") return; // PoC
if (event.data === 'PING') {
iframeWindow = event.source;
console.log('PONG');
}
}, false);
document.querySelector('input').onchange = ({target}) => {
if (!iframeWindow) return;
iframeWindow.postMessage(target.checked
? CSSStyleSheet.prototype.sayHi.toString()
: null,
'*'); // augment the domain here
};
<button>Say Outer Hi!</button>
<label><b>INCEPTION MODE</b><input type="checkbox" /></label><br/>
The key part here is passing the stringified function from host to iframe through postMessage mechanism. It can (and should) be hardened:
using proper domain instead of '*' on postMessage and checking event.origin within eventListener is A MUST; never ever use postMessage in production without that!
eval can be replaced with new Function(...) with some additional parsing for that handler code; as that prototype function should live until the page does, GC shouldn't be a problem.
Still, using this bridge may not be particularly less complicated than the approach you employ right now.
Your code should work.
You can also call it using sheet.__proto__.sayHi()
Your code (as written in the question) will work, because you are modifying the prototype object that is linked to by all instances of CSSStyleSheet (no matter when they were created).
The reference to the prototype object (more precisely: the [[Prototype]]) is examined dynamically every time a property look-up is attempted on an object without an own property that matches the requested property name. An own property is a property directly situated on an object.
In your case you are using the dot property accessor syntax sheet.sayHi. Property sayHi is not found as an own property, and so the prototype chain is traversed. It is then found on the prototype object that you modified on line 1. You then invoke the method located on that property using (), and 'CSSStyleSheet says hi!' is printed out.
Try it!
CSSStyleSheet.prototype.sayHi = function() {
console.log('CSSStyleSheet says hi!');
};
const test = new CSSStyleSheet;
test.sayHi(); // Console output: CSSStyleSheet says hi!
const styleElm = document.querySelector('style'),
sheet = styleElm.sheet;
sheet.sayHi()

What's the correct way to send Javascript code along with rendered HTTP to a client?

Mid development I decided to switch to server-side rendering for a better control amongst other benefits. My web application is completely AJAX based, no url redirecting, so the idea here is a website that builds itself up
I just couldn't figure out the proper way to send javascript events/functions along with the html string, or should all the necessary javascript always be preloaded in the static files?
Let's say client clicks a pre-rendered button 'open table'
The server will make a query, build the html table and send it back, but this table also needs javascript triggers and functions to work properly, how are these sent, received and executed?
There are a couple of articles that mention to not use eval() in Javascript, is there any way around this? I don't want to have to preload unnecessary events for elements that don't yet exist
The server is Python and the Client is Javascript/JQuery
Theoretical example :
Client Base Javascript :
$("body").on("click", "#open_table", function() {
$.getJSON('/get_table', function(response){
$("#table_div").append(response.html);
eval(response.javascript()); //??
}
});
Python Server(views.py) :
def get_table(request):
data = {}
#String containing rendered html
data['html'] = get_render_table()
#String containing Javascript code?
data['javascript'] = TABLE_EVENTS_JAVASCRIPT
return HttpResponse(json.dumps(data),content_type='json')
Worth noting my question comes from an experimental/learning perspective
Update:
You can use jQuery.getScript() to lazy load JS. I think this solution is as close as you can get to run JS without using eval().
See this example:
jQuery.getScript("/path/to/script.js", function(data, textStatus, jqxhr) {
/* Code has been loaded and executed. */
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
and "/path/to/script.js" could be a string returned from $.getJOSN response.
Also, the documentation for getScrippt() has examples on how to handle errors and cache files.
Old Answer:
Using .on() attaches events to current and future DOM elements.
You can either attache events prior to DOM insertion or attache event after DOM insertion.
So in your example you can do something like:
$("body").on("click", "#open_table", function() {
$.getJSON('/get_table', function(response){
var code = $(response.html);
code.find(".elementToFind").on("click", function (){
// Code to be executed on click event
});
$("#table_div").append(code);
}
});
I did not test the code but I think it should work.
Assuming you can't just set up an event-binding function and then call it from the main script (the JavaScript you need can't be guessed ahead of time, for example) then one really easy way is just to append the JavaScript to the bottom of the returned HTML content within script tags. When it's appended along with the HTML, the script should simply execute, with no eval() required.
I can't swear that this would work in old browsers, but it's a trick I've used a couple of times, and I've had no problems with it in Firefox, Chrome, or any of the later IE versions.
I think I see what you're asking here, from my understanding you want to send the new "page" asynchorously, and render the new javascript and html. It looks like you already got your request/response down, so i'm not gonna go and talk about sending JSON objects, and the whole "how-to" of sending html and javascript because it looks like you got that part. To do what you want and to dynamically add your javascript in, this stackoverflow question looks like it has what you need
Is there a way to create a function from a string with javascript?
So pertaining to your example, here is how it would look when you recieve the JSON string from your python script:
$("body").on("click", "#open_table", function() {
$.getJSON('/get_table', function(response){
$("#table_div").append(response.html);
/* Create function from string */
var newFunction = Function(response.javascript['param_1'], response.javascript['param_2'], response.javascript['function']);
/* Execute our new function to test it */
newFunction();
}
});
*Your actual function contents would be the string: response.javascript['function']
*Your parameter names if any would be in separate strings ex: response.javascript['param_1']
That is almost a direct copy of the "String to function" code that you can see in the linked question, just replaced it with your relevant code. This code is also assuming that your object is sent with the response.javascript object containing an array with your actual function content and parameter names. I'm sure you could change the actual name of the var too, or maybe put it in an associative array or something that you can keep track of and rename. All just suggestions, but hopefully this works for you, and helps you with your problem.
I am also doing similar work in my project where I had to load partial html using ajax calls and then this partial HTML has elements which requires events to be attached. So my solution is to create a common method to make ajax calls and keep a js method name to be executed post ajax call in html response itself. For example my server returns below html
<input type="hidden" data-act="onPartialLoad" value="createTableEvents" />
<div>.........rest of html response.....<div>
Now in common method, look for input[type='hidden'][data-act='onPartialLoad'] and for each run the method name provided in value attribute (value="createTableEvents")
Dont Use Eval() method as it is not recommended due to security
issues. Check here.
you can run js method using window["method name"]...so here is a part of code that I use.
$.ajax(options).done(function (data) {
var $target = $("#table_div");
$target.fadeOut(function () {
$target.html(data);
$target.fadeIn(function () {
try {
$('input[data-act="onPartialLoad"]', $target).each(function () {
try {
//you can pass parameters in json format from server to be passed into your js method
var params = $(this).attr('params');
if (params == undefined) {
window[$(this).val()]();
}
else {
window[$(this).val()]($.parseJSON(htmlutil.htmlDecode(params)));
}
} catch (e) {
if (console && console.log) {
console.log(e.stack);
console.log($(this).val());
}
}
});
}
catch (e) {
console.log(e.stack);
}
});
});
});
use jQuery.getScript() (as suggested by Kalimah Apps) to load the required js files first.

Rendering React.js clientside webapp with PhantomJS

A friend has asked me to capture a client-side rendered website built with React.js, preferably using PhantomJS. I'm using a simple rendering script as follows:
var system = require('system'),
fs = require('fs'),
page = new WebPage(),
url = system.args[1],
output = system.args[2],
result;
page.open(url, function (status) {
if (status !== 'success') {
console.log('FAILED to load the url');
phantom.exit();
} else {
result = page.evaluate(function(){
var html, doc;
html = document.querySelector('html');
return html.outerHTML;
});
if(output){
var rendered = fs.open(output,'w');
rendered.write(result);
rendered.flush();
rendered.close();
}else{
console.log(result);
}
}
phantom.exit();
});
The url is http://azertyjobs.tk
I consistently get an error
ReferenceError: Can't find variable: Promise
http://azertyjobs.tk/build/bundle.js:34
http://azertyjobs.tk/build/bundle.js:1 in t
...
Ok so I figured out that ES6 Promises aren't natively supported by PhantomJS yet, so I tried various extra packages like the following https://www.npmjs.com/package/es6-promise and initiated the variable as such:
var Promise = require('es6-promise').Promise
However this still produces the same error, although Promise is now a function. The output of the webpage is also still as good as empty (obviously..)
Now I'm pretty oldschool, so this whole client-side rendering stuff is kind of beyond me (in every aspect), but maybe someone has a solution. I've tried using a waiting script too, but that brought absolutely nothing. Am I going about this completely wrong? Is this even possible to do?
Much appreciated!
Ludwig
I've tried the polyfill you linked and it didn't work, changed for core.js and was able to make a screenshot. You need to inject the polyfill before the page is opened:
page.onInitialized = function() {
if(page.injectJs('core.js')){
console.log("Polyfill loaded");
}
}
page.open(url, function (status) {
setTimeout(function(){
page.render('output.jpg');
phantom.exit();
}, 3000);
});
What you need to understand is that there are several parts of a page loading. First there is the HTML - the same thing you see when you "view source" on a web page. Next there are images and scripts and other resources loaded. Then the scripts are executed, which may or may not result in more content being loaded and possible modifications to the HTML.
What you must do then is figure out a way to determine when the page is actually "loaded" as the user sees it. PhantomJS provides a paradigm for you to waitFor content to load. Read through their example and see if you can figure out a method which works for you. Take special note of where they put phantom.exit(); as you want to make sure that happens at the very end. Good luck.
Where (how) are you trying to initialise Promise? You'll need to create it as a property of window, or use es6-promise as a global polyfill, like this require('es6-promise').polyfill(); or this require('es6-promise/auto'); (from the readme).
Also, what do you mean by "capture"? How If you're trying to scrape data, you may have better luck using X-ray. It supports Phantom, Nightmare and other drivers.
Keep in mind also that React can also be server rendered. React is like templating, but with live data bindings. It's not as complicated as you're making it out to be.

How to edit console using javascript [duplicate]

So apparently because of the recent scams, the developer tools is exploited by people to post spam and even used to "hack" accounts. Facebook has blocked the developer tools, and I can't even use the console.
How did they do that?? One Stack Overflow post claimed that it is not possible, but Facebook has proven them wrong.
Just go to Facebook and open up the developer tools, type one character into the console, and this warning pops up. No matter what you put in, it will not get executed.
How is this possible?
They even blocked auto-complete in the console:
I'm a security engineer at Facebook and this is my fault. We're testing this for some users to see if it can slow down some attacks where users are tricked into pasting (malicious) JavaScript code into the browser console.
Just to be clear: trying to block hackers client-side is a bad idea in general;
this is to protect against a specific social engineering attack.
If you ended up in the test group and are annoyed by this, sorry.
I tried to make the old opt-out page (now help page) as simple as possible while still being scary enough to stop at least some of the victims.
The actual code is pretty similar to #joeldixon66's link; ours is a little more complicated for no good reason.
Chrome wraps all console code in
with ((console && console._commandLineAPI) || {}) {
<code goes here>
}
... so the site redefines console._commandLineAPI to throw:
Object.defineProperty(console, '_commandLineAPI',
{ get : function() { throw 'Nooo!' } })
This is not quite enough (try it!), but that's the
main trick.
Epilogue: The Chrome team decided that defeating the console from user-side JS was a bug and fixed the issue, rendering this technique invalid. Afterwards, additional protection was added to protect users from self-xss.
I located the Facebook's console buster script using Chrome developer tools. Here is the script with minor changes for readability. I have removed the bits that I could not understand:
Object.defineProperty(window, "console", {
value: console,
writable: false,
configurable: false
});
var i = 0;
function showWarningAndThrow() {
if (!i) {
setTimeout(function () {
console.log("%cWarning message", "font: 2em sans-serif; color: yellow; background-color: red;");
}, 1);
i = 1;
}
throw "Console is disabled";
}
var l, n = {
set: function (o) {
l = o;
},
get: function () {
showWarningAndThrow();
return l;
}
};
Object.defineProperty(console, "_commandLineAPI", n);
Object.defineProperty(console, "__commandLineAPI", n);
With this, the console auto-complete fails silently while statements typed in console will fail to execute (the exception will be logged).
References:
Object.defineProperty
Object.getOwnPropertyDescriptor
Chrome's console.log function (for tips on formatting output)
I couldn't get it to trigger that on any page. A more robust version of this would do it:
window.console.log = function(){
console.error('The developer console is temp...');
window.console.log = function() {
return false;
}
}
console.log('test');
To style the output: Colors in JavaScript console
Edit Thinking #joeldixon66 has the right idea: Disable JavaScript execution from console « ::: KSpace :::
Besides redefining console._commandLineAPI,
there are some other ways to break into InjectedScriptHost on WebKit browsers, to prevent or alter the evaluation of expressions entered into the developer's console.
Edit:
Chrome has fixed this in a past release. - which must have been before February 2015, as I created the gist at that time
So here's another possibility. This time we hook in, a level above, directly into InjectedScript rather than InjectedScriptHost as opposed to the prior version.
Which is kind of nice, as you can directly monkey patch InjectedScript._evaluateAndWrap instead of having to rely on InjectedScriptHost.evaluate as that gives you more fine-grained control over what should happen.
Another pretty interesting thing is, that we can intercept the internal result when an expression is evaluated and return that to the user instead of the normal behavior.
Here is the code, that does exactly that, return the internal result when a user evaluates something in the console.
var is;
Object.defineProperty(Object.prototype,"_lastResult",{
get:function(){
return this._lR;
},
set:function(v){
if (typeof this._commandLineAPIImpl=="object") is=this;
this._lR=v;
}
});
setTimeout(function(){
var ev=is._evaluateAndWrap;
is._evaluateAndWrap=function(){
var res=ev.apply(is,arguments);
console.log();
if (arguments[2]==="completion") {
//This is the path you end up when a user types in the console and autocompletion get's evaluated
//Chrome expects a wrapped result to be returned from evaluateAndWrap.
//You can use `ev` to generate an object yourself.
//In case of the autocompletion chrome exptects an wrapped object with the properties that can be autocompleted. e.g.;
//{iGetAutoCompleted: true}
//You would then go and return that object wrapped, like
//return ev.call (is, '', '({test:true})', 'completion', true, false, true);
//Would make `test` pop up for every autocompletion.
//Note that syntax as well as every Object.prototype property get's added to that list later,
//so you won't be able to exclude things like `while` from the autocompletion list,
//unless you wou'd find a way to rewrite the getCompletions function.
//
return res; //Return the autocompletion result. If you want to break that, return nothing or an empty object
} else {
//This is the path where you end up when a user actually presses enter to evaluate an expression.
//In order to return anything as normal evaluation output, you have to return a wrapped object.
//In this case, we want to return the generated remote object.
//Since this is already a wrapped object it would be converted if we directly return it. Hence,
//`return result` would actually replicate the very normal behaviour as the result is converted.
//to output what's actually in the remote object, we have to stringify it and `evaluateAndWrap` that object again.`
//This is quite interesting;
return ev.call (is, null, '(' + JSON.stringify (res) + ')', "console", true, false, true)
}
};
},0);
It's a bit verbose, but I thought I put some comments into it
So normally, if a user, for example, evaluates [1,2,3,4] you'd expect the following output:
After monkeypatching InjectedScript._evaluateAndWrap evaluating the very same expression, gives the following output:
As you see the little-left arrow, indicating output, is still there, but this time we get an object. Where the result of the expression, the array [1,2,3,4] is represented as an object with all its properties described.
I recommend trying to evaluate this and that expression, including those that generate errors. It's quite interesting.
Additionally, take a look at the is - InjectedScriptHost - object. It provides some methods to play with and get a bit of insight into the internals of the inspector.
Of course, you could intercept all that information and still return the original result to the user.
Just replace the return statement in the else path by a console.log (res) following a return res. Then you'd end up with the following.
End of Edit
This is the prior version which was fixed by Google. Hence not a possible way anymore.
One of it is hooking into Function.prototype.call
Chrome evaluates the entered expression by calling its eval function with InjectedScriptHost as thisArg
var result = evalFunction.call(object, expression);
Given this, you can listen for the thisArg of call being evaluate and get a reference to the first argument (InjectedScriptHost)
if (window.URL) {
var ish, _call = Function.prototype.call;
Function.prototype.call = function () { //Could be wrapped in a setter for _commandLineAPI, to redefine only when the user started typing.
if (arguments.length > 0 && this.name === "evaluate" && arguments [0].constructor.name === "InjectedScriptHost") { //If thisArg is the evaluate function and the arg0 is the ISH
ish = arguments[0];
ish.evaluate = function (e) { //Redefine the evaluation behaviour
throw new Error ('Rejected evaluation of: \n\'' + e.split ('\n').slice(1,-1).join ("\n") + '\'');
};
Function.prototype.call = _call; //Reset the Function.prototype.call
return _call.apply(this, arguments);
}
};
}
You could e.g. throw an error, that the evaluation was rejected.
Here is an example where the entered expression gets passed to a CoffeeScript compiler before passing it to the evaluate function.
Netflix also implements this feature
(function() {
try {
var $_console$$ = console;
Object.defineProperty(window, "console", {
get: function() {
if ($_console$$._commandLineAPI)
throw "Sorry, for security reasons, the script console is deactivated on netflix.com";
return $_console$$
},
set: function($val$$) {
$_console$$ = $val$$
}
})
} catch ($ignore$$) {
}
})();
They just override console._commandLineAPI to throw security error.
This is actually possible since Facebook was able to do it.
Well, not the actual web developer tools but the execution of Javascript in console.
See this: How does Facebook disable the browser's integrated Developer Tools?
This really wont do much though since there are other ways to bypass this type of client-side security.
When you say it is client-side, it happens outside the control of the server, so there is not much you can do about it. If you are asking why Facebook still does this, this is not really for security but to protect normal users that do not know javascript from running code (that they don't know how to read) into the console. This is common for sites that promise auto-liker service or other Facebook functionality bots after you do what they ask you to do, where in most cases, they give you a snip of javascript to run in console.
If you don't have as much users as Facebook, then I don't think there's any need to do what Facebook is doing.
Even if you disable Javascript in console, running javascript via address bar is still possible.
and if the browser disables javascript at address bar, (When you paste code to the address bar in Google Chrome, it deletes the phrase 'javascript:') pasting javascript into one of the links via inspect element is still possible.
Inspect the anchor:
Paste code in href:
Bottom line is server-side validation and security should be first, then do client-side after.
Chrome changed a lot since the times facebook could disable console...
As per March 2017 this doesn't work anymore.
Best you can do is disable some of the console functions, example:
if(!window.console) window.console = {};
var methods = ["log", "debug", "warn", "info", "dir", "dirxml", "trace", "profile"];
for(var i=0;i<methods.length;i++){
console[methods[i]] = function(){};
}
My simple way, but it can help for further variations on this subject.
List all methods and alter them to useless.
Object.getOwnPropertyNames(console).filter(function(property) {
return typeof console[property] == 'function';
}).forEach(function (verb) {
console[verb] =function(){return 'Sorry, for security reasons...';};
});
However, a better approach is to disable the developer tool from being opened in any meaningful way
(function() {
'use strict';
Object.getOwnPropertyNames(console).filter(function(property) {
return typeof console[property] == 'function';
}).forEach(function (verb) {
console[verb] =function(){return 'Sorry, for security reasons...';};
});
window.addEventListener('devtools-opened', ()=>{
// do some extra code if needed or ...
// maybe even delete the page, I still like to add redirect just in case
window.location.href+="#";
window.document.head.innerHTML="";
window.document.body.innerHTML="devtools, page is now cleared";
});
window.addEventListener('devtools-closed', ()=>{
// do some extra code if needed
});
let verifyConsole = () => {
var before = new Date().getTime();
debugger;
var after = new Date().getTime();
if (after - before > 100) { // user had to resume the script manually via opened dev tools
window.dispatchEvent(new Event('devtools-opened'));
}else{
window.dispatchEvent(new Event('devtools-closed'));
}
setTimeout(verifyConsole, 100);
}
verifyConsole();
})();
Internally devtools injects an IIFE named getCompletions into the page, called when a key is pressed inside the Devtools console.
Looking at the source of that function, it uses a few global functions which can be overwritten.
By using the Error constructor it's possible to get the call stack, which will include getCompletions when called by Devtools.
Example:
const disableDevtools = callback => {
const original = Object.getPrototypeOf;
Object.getPrototypeOf = (...args) => {
if (Error().stack.includes("getCompletions")) callback();
return original(...args);
};
};
disableDevtools(() => {
console.error("devtools has been disabled");
while (1);
});
an simple solution!
setInterval(()=>console.clear(),1500);
I have a simple way here:
window.console = function () {}
I would go along the way of:
Object.defineProperty(window, 'console', {
get: function() {
},
set: function() {
}
});
In Firefox it dosen't do that, since Firefox is a developer browser, I think since the command WEBGL_debug_renderer_info is deprecated in Firefox and will be removed. Please use RENDERER and the error Referrer Policy: Less restricted policies, including ‘no-referrer-when-downgrade’, ‘origin-when-cross-origin’ and ‘unsafe-url’, will be ignored soon for the cross-site request: https://static.xx.fbcdn.net/rsrc.php/v3/yS/r/XDDAHSZfaR6.js?_nc_x=Ij3Wp8lg5Kz.
This is not a security measure for weak code to be left unattended. Always get a permanent solution to weak code and secure your websites properly before implementing this strategy
The best tool by far according to my knowledge would be to add multiple javascript files that simply changes the integrity of the page back to normal by refreshing or replacing content. Disabling this developer tool would not be the greatest idea since bypassing is always in question since the code is part of the browser and not a server rendering, thus it could be cracked.
Should you have js file one checking for <element> changes on important elements and js file two and js file three checking that this file exists per period you will have full integrity restore on the page within the period.
Lets take an example of the 4 files and show you what I mean.
index.html
<!DOCTYPE html>
<html>
<head id="mainhead">
<script src="ks.js" id="ksjs"></script>
<script src="mainfile.js" id="mainjs"></script>
<link rel="stylesheet" href="style.css" id="style">
<meta id="meta1" name="description" content="Proper mitigation against script kiddies via Javascript" >
</head>
<body>
<h1 id="heading" name="dontdel" value="2">Delete this from console and it will refresh. If you change the name attribute in this it will also refresh. This is mitigating an attack on attribute change via console to exploit vulnerabilities. You can even try and change the value attribute from 2 to anything you like. If This script says it is 2 it should be 2 or it will refresh. </h1>
<h3>Deleting this wont refresh the page due to it having no integrity check on it</h3>
<p>You can also add this type of error checking on meta tags and add one script out of the head tag to check for changes in the head tag. You can add many js files to ensure an attacker cannot delete all in the second it takes to refresh. Be creative and make this your own as your website needs it.
</p>
<p>This is not the end of it since we can still enter any tag to load anything from everywhere (Dependent on headers etc) but we want to prevent the important ones like an override in meta tags that load headers. The console is designed to edit html but that could add potential html that is dangerous. You should not be able to enter any meta tags into this document unless it is as specified by the ks.js file as permissable. <br>This is not only possible with meta tags but you can do this for important tags like input and script. This is not a replacement for headers!!! Add your headers aswell and protect them with this method.</p>
</body>
<script src="ps.js" id="psjs"></script>
</html>
mainfile.js
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var ksExists = document.getElementById("ksjs");
if(ksExists) {
}else{ location.reload();};
var psExists = document.getElementById("psjs");
if(psExists) {
}else{ location.reload();};
var styleExists = document.getElementById("style");
if(styleExists) {
}else{ location.reload();};
}, 1 * 1000); // 1 * 1000 milsec
ps.js
/*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload!You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.
*/
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var mainExists = document.getElementById("mainjs");
if(mainExists) {
}else{ location.reload();};
//check that heading with id exists and name tag is dontdel.
var headingExists = document.getElementById("heading");
if(headingExists) {
}else{ location.reload();};
var integrityHeading = headingExists.getAttribute('name');
if(integrityHeading == 'dontdel') {
}else{ location.reload();};
var integrity2Heading = headingExists.getAttribute('value');
if(integrity2Heading == '2') {
}else{ location.reload();};
//check that all meta tags stay there
var meta1Exists = document.getElementById("meta1");
if(meta1Exists) {
}else{ location.reload();};
var headExists = document.getElementById("mainhead");
if(headExists) {
}else{ location.reload();};
}, 1 * 1000); // 1 * 1000 milsec
ks.js
/*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload! You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.
*/
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var mainExists = document.getElementById("mainjs");
if(mainExists) {
}else{ location.reload();};
//Check meta tag 1 for content changes. meta1 will always be 0. This you do for each meta on the page to ensure content credibility. No one will change a meta and get away with it. Addition of a meta in spot 10, say a meta after the id="meta10" should also be covered as below.
var x = document.getElementsByTagName("meta")[0];
var p = x.getAttribute("name");
var s = x.getAttribute("content");
if (p != 'description') {
location.reload();
}
if ( s != 'Proper mitigation against script kiddies via Javascript') {
location.reload();
}
// This will prevent a meta tag after this meta tag # id="meta1". This prevents new meta tags from being added to your pages. This can be used for scripts or any tag you feel is needed to do integrity check on like inputs and scripts. (Yet again. It is not a replacement for headers to be added. Add your headers aswell!)
var lastMeta = document.getElementsByTagName("meta")[1];
if (lastMeta) {
location.reload();
}
}, 1 * 1000); // 1 * 1000 milsec
style.css
Now this is just to show it works on all files and tags aswell
#heading {
background-color:red;
}
If you put all these files together and build the example you will see the function of this measure. This will prevent some unforseen injections should you implement it correctly on all important elements in your index file especially when working with PHP.
Why I chose reload instead of change back to normal value per attribute is the fact that some attackers could have another part of the website already configured and ready and it lessens code amount. The reload will remove all the attacker's hard work and he will probably go play somewhere easier.
Another note: This could become a lot of code so keep it clean and make sure to add definitions to where they belong to make edits easy in future. Also set the seconds to your preferred amount as 1 second intervals on large pages could have drastic effects on older computers your visitors might be using

Why does my Firefox extension not add event handlers using jQuery 1.4.2 object pulled from webpage in Firefox 4

My Firefox extension grabs a jQuery 1.4.2 object that is already embedded on a webpage and then tries to use that jQuery object to modify that page. It worked well in Firefox 3.x, but it does not seem to work in Firefox 4.
Here's my code:
window.addEventListener("load", function() { MyExt.init(); }, false);
var MyExt = {
targetHost: "somewebsite.com",
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if (appcontent){
appcontent.addEventListener("DOMContentLoaded", MyExt.onPageLoad, true);
}
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
var loc = doc.location;
var host = '';
if (loc.toString() != "about:blank") {
host = doc.location.host;
}
// Edit page
if (host == MyExt.targetHost) {
var $ = doc.defaultView.wrappedJSObject.$;
// this works
$('p').css('color', 'green');
// this works in Firefox 3.x, but does not work in Firefox 4
// instead it shows the following error:
// "Error: uncaught exception: TypeError: handler is undefined"
$('.sometextarea').keyup(function(event) { alert('it should work, but does not'); });
// even this does not work as expected
// it should display true, but it displays false
alert($.isFunction(function(){}));
}
}
What am I doing wrong?
Yes, you have to use wrappedJSObject due to API changes:
Specifying xpcnativewrappers=no in your manifest (that is, XPCNativeWrapper automation) is no longer supported. This was always intended to be a short-term workaround to allow extensions to continue to work while their authors updated their code to use XPCNativeWrappers.
If your add-on depends upon XBL bindings attached to content objects—for example, the ability to call functions or get and set properties created by the XBL binding—you will need to use the XPCNativeWrapper property wrappedJSObject to access wrapped objects.
If you need to be able to call functions or access properties defined by web content, you'll need to do this as well. This may be the case if, for example, you've written an extension that adds a delete button to a web mail service, and the service defines a window.delete() function that you need to call.
If, on the other hand, all you're doing with content is accessing DOM methods and properties, you've never needed to be using xpcnativewrappers=no in the first place, and should simply remove it from your manifest.

Categories