1- import { jsonToHTML , errorPage } from "./jsonformatter" ;
2- import { safeStringEncodeNums } from "./safe-encode-numbers" ;
3-
41/**
5- * This is the background script that runs independent of any document. It listens to main frame requests
6- * and kicks in if the headers indicate JSON. If we have the filterResponseData API available, we will use
7- * that to directly change the content of the response to HTML. Otherwise we interface with a content script
8- * to reformat the page.
2+ * This is the background script that runs independent of any document. It
3+ * listens to main frame requests and kicks in if the headers indicate JSON. If
4+ * we have the filterResponseData API available, we will use that to change the
5+ * page to what Chrome displays for JSON (this is only used in Firefox). Then a
6+ * content script reformats the page.
97 */
108
119// Look for JSON if the content type is "application/json",
@@ -32,17 +30,8 @@ function transformResponseToJSON(details: chrome.webRequest.WebResponseHeadersDe
3230 } ;
3331
3432 filter . onstop = ( _event : Event ) => {
35- let outputDoc = "" ;
36-
37- try {
38- const jsonObj = JSON . parse ( safeStringEncodeNums ( content ) ) ;
39- outputDoc = jsonToHTML ( jsonObj , details . url ) ;
40- } catch ( e : any ) {
41- outputDoc = errorPage ( e , content , details . url ) ;
42- }
43-
33+ const outputDoc = `<!DOCTYPE html><html><body><pre>${ content } </pre></body></html>` ;
4434 filter . write ( enc . encode ( outputDoc ) ) ;
45-
4635 filter . disconnect ( ) ;
4736 } ;
4837}
@@ -57,11 +46,10 @@ function detectJSON(event: chrome.webRequest.WebResponseHeadersDetails) {
5746 header . value &&
5847 jsonContentType . test ( header . value )
5948 ) {
49+ jsonUrls . add ( event . url ) ;
6050 if ( typeof browser !== "undefined" && "filterResponseData" in browser . webRequest ) {
6151 header . value = "text/html" ;
6252 transformResponseToJSON ( event ) ;
63- } else {
64- jsonUrls . add ( event . url ) ;
6553 }
6654 }
6755 }
@@ -77,16 +65,15 @@ chrome.webRequest.onHeadersReceived.addListener(
7765 [ "blocking" , "responseHeaders" ]
7866) ;
7967
68+ // Listen for a message from the content script to decide whether to
69+ // operate on the page. This is only necessary when the browser does
70+ // not support filterResponseData. Calls sendResponse with a boolean
71+ // that's true if the content script should run, and false otherwise.
8072chrome . runtime . onMessage . addListener ( ( _message , sender , sendResponse ) => {
8173 if ( sender . url ?. startsWith ( "file://" ) && sender . url . endsWith ( ".json" ) ) {
8274 sendResponse ( true ) ;
8375 return ;
8476 }
85- // If we support this API, we don't need to invoke the content script.
86- if ( "filterResponseData" in chrome . webRequest ) {
87- sendResponse ( false ) ;
88- return ;
89- }
9077 sendResponse ( sender . url && jsonUrls . has ( sender . url ) ) ;
9178 if ( sender . url ) {
9279 jsonUrls . delete ( sender . url ) ;
0 commit comments