Is it possible to know the target DOMWindow for an HTTPRequest? - javascript

I'm developing a firefox extension which requires me to intercept page loads by filtering out some HTTPRequests.
I did that using the instructions given here. Please note that my question draws from the content of this link.
I used the method given under the section of HTTPObservers. And it worked, I am indeed able to extract the respective urls of the Requests being sent out.
However, another thing which I really require is to get the target DOM Window where the contents pertaining to the HTTPRequest were about to be loaded. Is it possible using HTTPObservers?
In the link above, another way has been described using WebProgressListeners.
I tried that out as well. The onLocationChange() method only returns location changes in the url bar. Is it somehow possible to get the HTTPRequest urls using any of these progress listeners? Because if so, then if I understand correctly, aWebProgress.DOMWindow would give me the window I require.
Note: I am using gwt for the extension and the JSNI for the above mentioned part.

You can usually do that by using nsILoadContext interface (sadly barely documented) attached to the request or its load group. Here is how you would do that:
function getWindowForRequest(request)
{
if (request instanceof Components.interfaces.nsIRequest)
{
try
{
if (request.notificationCallbacks)
{
return request.notificationCallbacks
.getInterface(Components.interfaces.nsILoadContext)
.associatedWindow;
}
} catch(e) {}
try
{
if (request.loadGroup && request.loadGroup.notificationCallbacks)
{
return request.loadGroup.notificationCallbacks
.getInterface(Components.interfaces.nsILoadContext)
.associatedWindow;
}
} catch(e) {}
}
return null;
}
Note that this function is expected to return null occasionally - not every HTTP request is associated with a window.

Related

Best (and secure) way to call javascript function (with arguments) using a url from another page

After reviewing dozens of Stack Overflow posts, I'm thoroughly confused. What I am trying to do is create a URL through an tag on one page that would open another webpage and run a function that requires two arguments. I thought this would be simple but I keep seeing references to "cross site scripting vulnerabilities" and I am not familiar with this potential security problem and feel like I am now playing with fire. I do not want to utilize something — even if the code works — if it opens up security risks. Could someone point me in the right direction with the correct (and most secure) way to do this? I can do my research (and learning) from there. Much appreciated.
For example you can append some parameter at the end of your URL
https://your-url/?parameter=hello
When this URL is opened on another webpage you can run JavaScript or a PHP function based on that URL query.
For JavaScript
getUrlParam(slug) {
let url = new URL(window.location);
let params = new URLSearchParams(url.search);
let param = params.get(slug);
if (param) {
return param;
} else {
return false;
}
}
console.log(getUrlParam('parameter'));
After that, you can run this function to check if any parameter is passed in that URL or not.
If this function returns that's given slug parameter you can run your custom code inside that if condition block

Suppressing HTMLImageElement onerror [duplicate]

This question already has an answer here:
Check if file exists but prevent 404 error in console from showing up [duplicate]
(1 answer)
Closed 8 years ago.
I'm running a script that is dynamically loading images depending on a few criteria. The script does not know beforehand whether a specific image source actually exists and will thus need to check before displaying the image. I do this by replacing the onerror handler on the element with a function that attempts to gracefully handle the event.
At first glance this works rather well, however even though I have replaced the event, the browser still audits 404 errors in the console which I don't want. Even worse is that IE displays the infamous JS error icon in the status bar which I find rather awkward.
I've tried to summarise the problem in a JSFiddle.
var img = new Image();
img.onerror = function (ev) {
alert("This does not exist!");
return true;
}
img.onload = function (ev) {
document.body.appendChild(this);
}
img.src = "foo.png"; //Missing image
Basically, I want to suppress all error reporting for this element such that the console doesn't get flooded with superfluous error output.
I know that I could solve this by prefetching and evaluating the HTTP headers with AJAX and server side scripting, which while technically a possible solution, is something I would prefer to avoid. However, while I only use standard JS in my example, JQuery code is also acceptable.
I have tried reading up on the event specification, but since web scripting is still the mess of confusing ECMAScript, HTML DOM, client, pixy dust and now HTML5 definitions that we all love to hate, it really didn't make me any wiser. The closest I got was Mozilla's documentation (that interestingly doesn't even state the correct function parameters) which suggested that letting the event return true would suppress errors, but that didn't really work.
I believe you can not check if image link is broken/does not exist without getting 404 error. Which is actually is information about link is broken.
You mentioned that other way is ajax to check existance...
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status != 404;
}
UrlExists('img_url');
but still you will get 404 in console.

Is it possible for the admin to get the full sourcecode of my js-file if I redirect a Javascript file to a local modified Javascript file?

I created a google-chrome-extension which redirects all requests of a javascript-file on a website to a modified version of this file which is on my harddrive.
It works and I do it simplified like this:
... redirectUrl: chrome.extension.getURL("modified.js") ...
Modified.js is the same javascript file except that I modified a line in the code.
I changed something that looks like
var message = mytext.value;
to var message = aes.encrypt(mytext.value,"mysecretkey");
My question is now is it possible for the admin of this website where I redirect the javascript-file to modify his webpage that he can obtain "mysecretkey". (The admin knows how my extension works and which line is modified but doesn't know the used key)
Thanks in advance
Yes, the "admin" can read the source code of your code.
Your method is very insecure. There are two ways to read "mysecretkey".
Let's start with the non-trivial one: Get a reference to the source. Examples, assume that your aes.encrypt method looks like this:
(function() {
var aes = {encrypt: function(val, key) {
if (key.indexOf('whatever')) {/* ... */}
}};
})();
Then it can be compromised using:
(function(indexOf) {
String.prototype.indexOf = function(term) {
if (term !== 'known') (new Image).src = '/report.php?t=' + term;
return indexOf.apply(this, arguments);
};
})(String.prototype.indexOf);
Many prototype methods result in possible leaking, as well as arguments.callee. If the "admin" wants to break your code, he'll surely be able to achieve this.
The other method is much easier to implement:
var x = new XMLHttpRequest();
x.open('GET', '/possiblymodified.js');
x.onload = function() {
console.log(x.responseText); // Full source code here....
};
x.send();
You could replace the XMLHttpRequest method, but at this point, you're just playing the cat and mouse game. Whenever you think that you've secured your code, the other will find a way to break it (for instance, using the first described method).
Since the admin can control any aspect of the site, they could easily modify aes.encrypt to post the second argument to them and then continue as normal. Therefore your secret key would be immediately revealed.
No. The Web administrator would have no way of seeing what you set it to before it could get sent to the server where he could see it.

Implementing a chrome extension that filters HTTP methods

I'm trying to implement a Google Chrome extension that filters HTTP methods. My idea, for now, is just to display all kinds of HTTP requests that starts at the client side, one after the other. I found out the method chrome.experimental.webRequest.onBeforeRequest.addListener(interceptRequest, null, ['blocking']); which basically calls the interceptRequest method.
The interceptRequest method does the following:
function interceptRequest(request) {
console.log('onBeforeRequest ', request.url);
var p = document.createElement("p");
var text = document.createTextNode("" + request.url);
p.appendChild(text);
document.body.appendChild(p);
document.body.append(request.url);
}
Basically it still does nothing, but at least I would like to print me out the urls, to start doing something, but also this easy task seems not to work.
Does anybody have an idea on how to make that work? If that work, from the request variable I should be able to get out also the HTTP methods and conclude my work.
Thanks
I think you may be confusing the various script contexts that exist within a chrome extension.
take a look at this: http://code.google.com/chrome/extensions/overview.html#arch

How to load a greasemonkey script after AJAX-Request

I have a simple greasemonkey script that makes some simple dom manipulation. The greasemonkey script is loaded after the DOM is loaded, that's fine so fare and it does work for the initial Page. But on this site (it's twitter ;-) ) parts of the page get loaded after a click by xmlhttprequest and this part did not get manipulated by my greasemonkeyscript.
Is there a simple possibility to run the script again after the xmlhttprequest is loaded or after the DOM is changed by the request?
A powerful technique when using Greasemonkey is to 'hijack' existing JavaScript functions. If the page you are altering has a function called processAjaxResponse which is called when to process the XmlHttpRequest response, the you can do the following in your Greasemonkey script:
var originalProcessAjaxResponse;
function myNewProcessAjaxResponse() {
/* Manipulate DOM if you need to, and then... */
originalProcessAjaxResponse();
}
function hijack() {
var originalProcessAjaxResponse = processAjaxResponse;
processAjaxResponse = myNewProcessAjaxResponse();
}
This allows you to inject your own functionality when the AJAX response event occurs.
Thanks Howard. It was the way in the right direction.
It's quite hard to find the right entry point to hijack a function on a minifyied script. But I found that there is a huck in the twitter script. It does call window.onPageChange after the Ajax request. (I wonder if this is a common best practice in javascript and if other do this as well?) I did found some code on http://userscripts.org/scripts/review/47998 wich does use this posibility to attach events.
if (typeof unsafeWindow.onPageChange === 'function') {
var _onPageChange = unsafeWindow.onPageChange;
unsafeWindow.onPageChange = function(){
_onPageChange();
filter();
};
} else {
unsafeWindow.onPageChange = filter;
}

Categories

Resources