Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Injecting Javascript before page loads #138

Open
ghost opened this issue Apr 15, 2020 · 3 comments
Open

Injecting Javascript before page loads #138

ghost opened this issue Apr 15, 2020 · 3 comments

Comments

@ghost
Copy link

ghost commented Apr 15, 2020

How would I inject this javascript: alert('INJECTED') into a website being served? Also, can I intercept AJAX/Http requests from the website through the proxy?

Injecting Javascript using response middleware will inject the script for ALL the sites proxied through, right?

@nfriedly
Copy link
Owner

Yep, take a look at https://github.com/nfriedly/node-unblocker/blob/websockets/lib/client-scripts.js

I had to add that to catch websocket connections and force them to go through the proxy, and I have todo's for XMLHTTPRequest and fetch.

Everything in this section gets wrapped in an IIFE and injected right after the <head> tag:

/* eslint env: browser */
console.log("begin unblocker client scripts");
var _WebSocket = WebSocket;
var host = location.host;
var isSecure = location.protocol === "https";
var prefix = "PREFIX";
// ws:// or wss:// then at least one char for location,
// then either the end or a path
reWsUrl = /ws(s?):\/\/([^\/]+)($|\/.*)/;
window.WebSocket = function(url, protocols) {
var parsedUrl = url.match(reWsUrl);
if (parsedUrl) {
var wsSecure = parsedUrl[1];
// force downgrade if wss:// is called on insecure page
// (in case the proxy only supports http)
var wsProto = isSecure ? "ws" + wsSecure + "://" : "ws://";
var wsHost = parsedUrl[2];
var wsPath = parsedUrl[3];
if (wsHost === host) {
// let the server figure out the path
// todo: get the remote host and fix this
return new _WebSocket(wsProto + wsHost + wsPath, protocols);
}
// prefix the websocket with the proxy server
return new _WebSocket(
wsProto + host + prefix + "http" + wsSecure + "://" + wsHost + wsPath
);
}
// fallback in case the regex failed
return new _WebSocket(url, protocols);
};

Note that websockets always require a complete url (including the domain), which would bypass the proxy without this, but XMLHttpRequest and fetch allow for relative URLs which would go to the proxy and just work (sometimes).

@ghost
Copy link
Author

ghost commented Apr 15, 2020

Is it possible to add scripts as a configuration option? Would I put the function I want to inject into the response middleware as a string or something?

@nfriedly
Copy link
Owner

nfriedly commented Apr 15, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant