Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject Javascript into a site, then make sure it's cross-browser compatible?

I am doing some contract work in which I need to write small snippets of Javascript for client sites and then make sure that they work in all browsers.

I don't have access to the sites' servers themselves, so I need to be able to inject the snippets some other way.

I tried writing a proxy script in PHP that grabs the site's source code, absolutizes all the URLs, and then injects the Javascript, and that works for some client sites (and has the advantage of being easily testable in multiple browsers).

But some Javascript-heavy sites don't work with this approach -- they'll do stuff like testing the window.location to make sure it isn't spoofed, or they'll include references to files on the local server that the proxy script isn't able to filter.

As an alternative, I suppose I could use Greasemonkey to inject the Javascript ... which would let me see how the code looks in Firefox, but then how do I test in, say, IE6?

Can anyone suggest a way to do cross-browser Javascript development when you don't have access to the site on which the Javascript will eventually reside?

like image 512
jawns317 Avatar asked Dec 27 '22 18:12

jawns317


2 Answers

You can use a bookmarklet to insert your JavaScript by injecting a script tag.

The code itself would look something like this:

(function() {
    var d = document,
        s = d.createElement('script'),
        t = d.body || d.getElementsByTagName('head')[0] || d.documentElement;
    s.src = "http://path/to/your/script.js";
    t.appendChild(s);
})();

Then just bookmark-ify it (search for "bookmarklet maker" and you'll find a bunch to do the work for you). You bookmark the result, visit the page you want to test on, and click your bookmark to do your testing.

For instance:

javascript:(function(){%28function%28%29%20%7Bvar%20d%20%3D%20document%2Cs%20%3D%20d.createElement%28%27script%27%29%2Ct%20%3D%20d.body%20%7C%7C%20d.getElementsByTagName%28%27head%27%29%5B0%5D%20%7C%7C%20d.documentElement%3Bs.src%20%3D%20%22http%3A//jsbin.com/ajubo4%22%3Bt.appendChild%28s%29%3B%7D%29%28%29%3B})();

If you copy that into a bookmark's URL, when you activate the bookmark on any major browser it loads a simple script from http://jsbin.com (which you can find here) that does an alert telling you how many p elements are on the page. (There are, at the moment, 23 on this page.)

like image 123
T.J. Crowder Avatar answered Jan 11 '23 23:01

T.J. Crowder


One fast and simple solution, is to use Privoxy.

like image 35
AlexR Avatar answered Jan 12 '23 00:01

AlexR