Search code examples
javascriptcssnode.jsdom-manipulation

Advice on proxying CSS and JS with a Node.js "proxy" server


I have a working server for entering a URL in a query parameter, it fetches the page and sends it back. The problem is, the CSS links don't always work because generally CSS is fetched from the source by the HTML <link rel="stylesheet"> tag. Is there a way I can fetch the CSS from the URL and send it in a <style> tag?

I'd like to be able to do this with JavaScript as well, but it is not a requirement.

Additionally, as a "nice-to-have", is it possible to change anchor href tags to change the query parameter instead of URL itself? privatedomain.com/page?url=<urlhere> is the URL structure I have, and would like it to be able to redirect from something like privatedomain.com/page?url=http://www.google.com to privatedomain.com/page?url=http://www.google.com/search?q=hmm+yes

Really just a thing I'm doing for fun and trying to get it to work, if I asked this question incorrectly, I'm sorry, it's my first time asking here, thanks!


Solution

  • Parse the document, find <link rel="stylesheet">, extract the relative path to CSS from there.

    Then you can concatenate the relative path with the root of your <urlhere>. Then replace a link inside <link rel="stylesheet"> with your combined path.

    Example: privatedomain.com/page?url=http://example.com/foo/bar.html

    in foo.html you have <link rel="stylesheet" href="/styles.css">

    You need to make const absoulteCssPath = 'http://example.com' + '/styles.css'; and then replace /styles.css inside <link rel="stylesheet" href="/styles.css"> with your absoulteCssPath.