Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit Chrome extension content script to a specific content types?

Is it possible to make content script injected only if document's content type matches specific pattern? Actually, my goal is much simpler: I need my content script injected to HTML documents only (for now, it's injected in XML docs as well). Content scripts must be injected at "document_start".

like image 804
Michael Spector Avatar asked Nov 14 '22 11:11

Michael Spector


1 Answers

I came to a similar problem and solved it in the following way.

Instead of limiting variety of documents where a content script is injected, based on documents' Content-Type, I decided to inject the script into all documents, but execute it in proper ones only.

This is done by analysing document.xmlVersion and document.doctype properties:

  • document.doctype must be not null in an HTML document;
  • document.xmlVersion must be not null in an XML document;

So, it is easy to use either of them to distinguish one type from another and "bind" all necessary script stuff only when appropriate. In particular, one can inject small script loader, which will load additional, possibly heavy stuff, conditionally.

Chrome does not still provide any means for limiting script injection by document type.

like image 53
Stan Avatar answered Nov 17 '22 00:11

Stan