Monday, June 3, 2024
-1
rated 0 times [  1] [ 2]  / answers: 1 / hits: 31170  / 12 Years ago, mon, april 9, 2012, 12:00:00

I work on a javascript library that customers include on their site to embed a UI widget. I want a way to test dev versions of the library live on the customer's site without requiring them to make any changes to their code. This would make it easy to debug issues and test new versions.



To do this I need to change the script include to point to my dev server, and then override the load() method that's called in the page to add an extra parameter to tell it what server to point to when making remote calls.



It looks like I can add JS to the page using a chrome extension, but I don't see any way to modify the page before it's loaded. Is there something I'm missing, or are chrome extensions not allowed to do this kind of thing?


More From » google-chrome

 Answers
16

I've done a fair amount of Chrome extension development, and I don't think there's any way to edit a page source before it's rendered by the browser. The two closest options are:




  • Content scripts allow you to toss in extra JavaScript and CSS files. You might be able to use these scripts to rewrite existing script tags in the page, but I'm not sure it would work out, since any script tags visible to your script through the DOM are already loaded or are being loaded.


  • WebRequest allows you to hijack HTTP requests, so you could have an extension reroute a request for library.js to library_dev.js.




Assuming your site is www.mysite.com and you keep your scripts in the /js directory:



chrome.webRequest.onBeforeRequest.addListener(
function(details) {
if( details.url == http://www.mysite.com/js/library.js )
return {redirectUrl: http://www.mysite.com/js/library_dev.js };
},
{urls: [*://www.mysite.com/*.js]},
[blocking]);


The HTML source will look the same, but the document pulled in by <script src=library.js></script> will now be a different file. This should achieve what you want.


[#86358] Friday, April 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzjenseny

Total Points: 409
Total Questions: 93
Total Answers: 106

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;