Sniffer.sys.mjs (2045B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs"; 6 7 const gPrefs = {}; 8 9 XPCOMUtils.defineLazyPreferenceGetter( 10 gPrefs, 11 "gEnabled", 12 "devtools.jsonview.enabled" 13 ); 14 15 const JSON_VIEW_MIME_TYPE = "application/vnd.mozilla.json.view"; 16 17 function getContentDisposition(channel) { 18 try { 19 return channel.contentDisposition; 20 } catch (e) { 21 // Channel doesn't support content dispositions 22 return null; 23 } 24 } 25 26 /** 27 * This component represents a sniffer (implements nsIContentSniffer 28 * interface) responsible for changing top level 'application/json' 29 * document types to: 'application/vnd.mozilla.json.view'. 30 * 31 * This internal type is consequently rendered by JSON View component 32 * that represents the JSON through a viewer interface. 33 * 34 * This is done in the .js file rather than a .jsm to avoid creating 35 * a compartment at startup when no JSON is being viewed. 36 */ 37 export class Sniffer { 38 getMIMETypeFromContent(request) { 39 if (request instanceof Ci.nsIChannel) { 40 // JSON View is enabled only for top level loads only. 41 if ( 42 gPrefs.gEnabled && 43 request.loadInfo?.isTopLevelLoad && 44 request.loadFlags & Ci.nsIChannel.LOAD_DOCUMENT_URI && 45 getContentDisposition(request) != Ci.nsIChannel.DISPOSITION_ATTACHMENT 46 ) { 47 // Check the response content type and if it's a valid type 48 // such as application/json or application/manifest+json 49 // change it to new internal type consumed by JSON View. 50 if (/^application\/(?:.+\+)?json$/.test(request.contentType)) { 51 return JSON_VIEW_MIME_TYPE; 52 } 53 } else if (request.contentType === JSON_VIEW_MIME_TYPE) { 54 return "application/json"; 55 } 56 } 57 58 return ""; 59 } 60 } 61 62 Sniffer.prototype.QueryInterface = ChromeUtils.generateQI([ 63 "nsIContentSniffer", 64 ]);