alesdario
alesdario

Reputation: 1894

PhantomJS Change JS src before he starts loading

I'trying to change Javascript src in order to get a "dev environment" for testing some Javascripts.

( Obviously i can't build a real dev environment , i can't mirror this website on a dev env ).

So i was thinking about manipulating Dom with PhantomJS and testing javascript with CasperJS. I wanna convert ( for example ) this script

<script type="..." language="..." src="production_path/source.js"></script>

into this one

<script type="..." language="..." src="dev_path/source.js"></script>

before the script starts loading.

I'm trying with

casper.start("http://www.example.com/",function(status){


        var scripts = document.getElementsByTagName('script');

        casper.each(scripts,function(self,my_script){

            //here i would rewrite script url

        });

});

casper.run();

but it doesn't work. I'm afraid i have to wait for something , but i'm not understanding what.

Upvotes: 2

Views: 529

Answers (1)

Darren Cook
Darren Cook

Reputation: 28913

Taking a step back, is it okay to re-phrase your question as: how do I get PhantomJS to load "dev_path/source.js" when it tries to load "production_path/source.js"?

If so, write a onResourceRequested handler, and use the changeUrl function of the resourceRequest object.

It will be something like this:

casper.page.onResourceRequested = function(requestData, networkRequest) {
  if(requestData.url == 'production_path/source.js'){
    console.log("Changing request from production to dev for source.js");
    networkRequest.changeUrl('dev_path/source.js');
    }
};

Of course in a real situation I'd use a regex replace (as I expect there are multiple URLs to replace).

(Untested, so let me know if it does not work, and I'll look into it more carefully.)

Upvotes: 2

Related Questions