Content_scripts vs background

For a thing I am making I need to do a bunch of regex in background scripts and it got me wondering, is their any reason to not just use background instead of background and content_scripts together?

If I were to use content_scripts, I would be listening on all url’s (and loading a big chunk of JS into the page anyway). With background, I can use browser.tabs.executeScript to call javascript so it acts like content_scripts. Plus since I’m just listening for the url I don’t have to load any JS until my regex has been matched.

Is there any downside to this?

Example:

var c = new RegExp('https?\:\/\/(www\.)?bla\.com', 'ig');

function a(i) {
	if(c.test(i.url)) {
	        console.log("a: " + i.url);
	}
}

function b(i) {
	if(c.test(i.url)) {
		console.log("b: " + i.url);
	}
}


browser.webNavigation.onCommitted.addListener(a);
browser.webRequest.onHeadersReceived.addListener(
	b,
	{
		urls: ['*://*/*'],
		types: ['main_frame']
	},
	['blocking', 'responseHeaders']
);

If you only expect to actually run scripts in a small portion of all loaded pages, you should definitely do that.

If possible, you should restrict your listeners to the urls you care about. And if this is only about injecting content script, webNavigation is what you want instead of webRequest.

Content script injection from manifest should only be used if every page needs to have it. Otherwise, tabs.executeScript is more efficient.

Good to know, thanks!