Prevent zombie.js from loading only external resources
Asked Answered
P

3

5

I am using zombie.js to load a page from a local express server during a test. Unfortunately, there is a script element which calls out to Google Analytics. I would like to block this external script (gracefully) without preventing other (local) scripts from loading, if possible.

I know that { runScripts : false } is available with calls to browser.visit(). However, that refuses to load any and all scripts on the page, not just those living on other hosts. Is this possible?

Pleione answered 22/3, 2013 at 21:53 Comment(0)
P
7

You should use the resources object.

You can set certain requests to give specific responses if you don't want the request to actually go through. You'd do the following to make google analytics return an empty document:

browser.resources.mock('http://google.com/url/to/analytics.js',{});

Note that you have to provide the exact URL that you want to mock, there is no way to mock a partial URL such as a domain name.

Petiolate answered 30/4, 2013 at 18:12 Comment(1)
It seems to me the resources.mock method is no longer present in zombie 4.x. See github.com/assaf/zombie/blob/master/src/resources.jsJuggins
J
8

Since zombie 3.1, the browser.resources.mock method is gone. The alternative is to use nock library:

var nock = require('nock')

nock('http://www.google-analytics.com')
  .get('/analytics.js')
  .times(Math.Infinity)
  .reply(200, '{}')

var Browser = require('zombie')
var browser = new Browser()
Juggins answered 3/6, 2015 at 17:42 Comment(0)
P
7

You should use the resources object.

You can set certain requests to give specific responses if you don't want the request to actually go through. You'd do the following to make google analytics return an empty document:

browser.resources.mock('http://google.com/url/to/analytics.js',{});

Note that you have to provide the exact URL that you want to mock, there is no way to mock a partial URL such as a domain name.

Petiolate answered 30/4, 2013 at 18:12 Comment(1)
It seems to me the resources.mock method is no longer present in zombie 4.x. See github.com/assaf/zombie/blob/master/src/resources.jsJuggins
W
1

Maybe something like this would work for you? It loops through all resources and "aborts" the ones that should be ignored.

const Fetch = require('zombie/lib/fetch');

const ignoredResources = [
  'google-analytics.com'
];

browser.pipeline.addHandler((browser, request) => {
  let doAbort = false;

  ignoredResources.forEach(domain => {
    if (request.url.includes(domain)) {
      doAbort = true;
    }
  });

  if (doAbort) {
    return new Fetch.Response('', { status: 200 });
  }
});
Wickerwork answered 16/8, 2017 at 5:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.