Safe Rendering of User Content
This content might contain dangerous markup.
Readability strips scripts, but for untrusted input always sanitize the output too.
### Handle CPU Profiling in Instance Source: https://github.com/mozilla/readability/blob/main/test/test-pages/lazy-image-1/expected.html Example code demonstrating how to handle incoming messages to start and stop CPU profiling within a Node.js instance. ```javascript const WebSocket = require('ws'); const inspector = require('inspector'); const ws = new WebSocket('ws://localhost:8080'); // Connect to the signaling server ws.on('open', () => { console.log('Connected to signaling server'); ws.send('start-profiling'); // Example: Send a message to start profiling }); ws.on('message', (message) => { console.log(`Received message from server: ${message}`); if (message === 'start-profiling') { console.log('Starting CPU profiling...'); inspector.startProfiling(); } else if (message === 'stop-profiling') { console.log('Stopping CPU profiling...'); const profile = inspector.stopProfiling(); console.log('Profiling data:', JSON.stringify(profile, null, 2)); // Here you can send the profile data back or save it } }); ws.on('error', (error) => { console.error('WebSocket error:', error); }); ws.on('close', () => { console.log('Disconnected from signaling server'); }); // Example of how to programmatically start/stop profiling if not using WebSocket messages // inspector.startProfiling(); // setTimeout(() => { // const profile = inspector.stopProfiling(); // console.log('Programmatic profile:', JSON.stringify(profile, null, 2)); // }, 5000); // Profile for 5 seconds ``` -------------------------------- ### Folder Description JSON-LD Example Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/source.html This example shows the expected JSON-LD structure for a successful GET request to a folder. It includes context, and an 'items' map detailing contained documents and subfolders with their metadata. ```json { "@context": "[http://remotestorage.io/spec/folder-description](http://remotestorage.io/spec/folder-description)", "items": { "abc": { "ETag": "DEADBEEFDEADBEEFDEADBEEF", "Content-Type": "image/jpeg", "Content-Length": 82352 }, "def/": { "ETag": "1337ABCD1337ABCD1337ABCD" } } } ``` -------------------------------- ### Install inspector-api Source: https://github.com/mozilla/readability/blob/main/test/test-pages/lazy-image-1/expected.html Install the inspector-api module to enable async/await syntax for CPU profiling. ```bash npm install inspector-api --save ``` -------------------------------- ### GET Operation Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/source.html Demonstrates how to retrieve data or folder descriptions using the GET method. Includes examples for successful retrieval (200 OK) and handling of unchanged resources (304 Not Modified). ```APIDOC ## GET /storage/michiel/myfavoritedrinks/ ### Description Retrieves a folder description. ### Method GET ### Endpoint /storage/michiel/myfavoritedrinks/ ### Request Example Referer: [https://drinks-unhosted.5apps.com/?](https://drinks-unhosted.5apps.com/?) If-None-Match: "1382694045000", "1382694048000" ### Response #### Success Response (200) - **name** (string) - The name of the item. - **updated** (boolean) - Indicates if the item has been updated. - **@context** (string) - The context of the item. #### Response Example HTTP/1.1 200 OK Access-Control-Allow-Origin: [https://drinks-unhosted.5apps.com](https://drinks-unhosted.5apps.com) Content-Type: application/json; charset=UTF-8 Content-Length: 106 ETag: "1382694048000" Expires: 0 {"name":"test", "updated":true, "@context":"http://remotestorage.io/spec/modules/myfavoritedrinks/drink"} ## GET /storage/michiel/myfavoritedrinks/ ### Description Retrieves a folder description when the URL points to a folder. ### Method GET ### Endpoint /storage/michiel/myfavoritedrinks/ ### Response #### Success Response (200) - **@context** (string) - The context of the folder description. - **items** (object) - An object containing details of items within the folder. - **item_name** (object) - Details for a specific item. - **ETag** (string) - The ETag of the item. - **Content-Type** (string) - The Content-Type of the item. - **Content-Length** (integer) - The Content-Length of the item. #### Response Example HTTP/1.1 200 OK Access-Control-Allow-Origin: [https://drinks-unhosted.5apps.com](https://drinks-unhosted.5apps.com) Content-Type: application/ld+json Content-Length: 171 ETag: "1382694048000" Expires: 0 {"@context":"[http://remotestorage.io/spec/folder-version](http://remotestorage.io/spec/folder-version)","items":{"test":{"ETag":"1382694048000","Content-Type":"application/json; \ncharset=UTF-8","Content-Length":106}}} ## GET /storage/michiel/myfavoritedrinks/x ### Description Handles requests for non-existing documents. ### Method GET ### Endpoint /storage/michiel/myfavoritedrinks/x ### Response #### Not Found Response (404) - No ETag header is returned. #### Response Example HTTP/1.1 404 Not Found Access-Control-Allow-Origin: [https://drinks-unhosted.5apps.com](https://drinks-unhosted.5apps.com) ``` -------------------------------- ### iFrame Resizing Initialization Example Source: https://github.com/mozilla/readability/blob/main/test/test-pages/cnn/source.html Example of how to initialize iFrame resizing with specific options for an iframe element. ```javascript iFrameResizeSA({ log: false, checkOrigin: false }, document.getElementById('sa_swtYhka26oGQ')); ``` -------------------------------- ### Install Readability.js Source: https://github.com/mozilla/readability/blob/main/README.md Install the Readability.js library using npm. This command is used in Node.js environments. ```bash npm install @mozilla/readability ``` -------------------------------- ### HTTP GET Response for a Folder Description Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/source.html Example of a 200 OK response for a GET request to a folder URL, returning a JSON-LD folder description. Used to list contents and their metadata. ```http HTTP/1.1 200 OK Access-Control-Allow-Origin: [https://drinks-unhosted.5apps.com](https://drinks-unhosted.5apps.com) Content-Type: application/ld+json Content-Length: 171 ETag: "1382694048000" Expires: 0 {"@context":"[http://remotestorage.io/spec/folder-version](http://remotestorage.io/spec/folder-version)","items":{"test":{"ETag":"1382694048000","Content-Type":"application/json; \ncharset=UTF-8","Content-Length":106}}} ``` -------------------------------- ### Creating a Simple GET Request Source: https://github.com/mozilla/readability/blob/main/test/test-pages/002/expected.html Shows the basic instantiation of a Request object for fetching a resource via GET. The method defaults to 'GET' if not specified. ```javascript var req = new Request("/index.html"); console.log(req.method); // "GET" console.log(req.url); // "http://example.com/index.html" ``` -------------------------------- ### OAuth Dialog Request Example Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/source.html An example GET request to an OAuth endpoint for obtaining a bearer token, including redirect URI and scope parameters. ```http GET /oauth/michiel?redirect_uri=https%3A%2F%2Fdrinks-unhosted.5\n ``` -------------------------------- ### Implement and Publish a New Feature with a Bookmark Source: https://github.com/mozilla/readability/blob/main/test/test-pages/mercurial/source.html Bob creates a bookmark 'featureX', stages a file, and commits the first version of his feature. He then pushes this bookmarked head to the review repository. ```bash $ cd ../bob $ echo 'stuff' > file1 $ hg bookmark featureX $ hg commit -u bob -m 'implement feature X (v1)' $ hg push -B featureX ``` -------------------------------- ### Implement and Publish New Feature (v1) Source: https://github.com/mozilla/readability/blob/main/test/test-pages/mercurial/expected.html Bob creates a bookmark for a new feature, commits an initial version, and pushes it to the review repository. ```bash $ cd ../bob $ echo 'stuff' > file1 $ hg bookmark featureX $ hg commit -u bob -m 'implement feature X (v1)' # rev 4:1636 $ hg push -B featureX [...] added 1 changesets with 1 changes to 1 files (+1 heads) exporting bookmark featureX ``` -------------------------------- ### HTTP GET Response for a Document Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/source.html Example of a 200 OK response for a GET request, including ETag and content details. Used when retrieving a specific document. ```http HTTP/1.1 200 OK Access-Control-Allow-Origin: [https://drinks-unhosted.5apps.com](https://drinks-unhosted.5apps.com) Content-Type: application/json; charset=UTF-8 Content-Length: 106 ETag: "1382694048000" Expires: 0 {"name":"test", "updated":true, "@context":"http://remotestora\nge.io/spec/modules/myfavoritedrinks/drink"} ``` -------------------------------- ### GET Folder Description Response Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/expected.html Example of a GET request for a folder, where the server responds with a folder description in JSON-LD format. This response includes metadata about the items within the folder. ```http HTTP/1.1 200 OK Access-Control-Allow-Origin: https://drinks-unhosted.5apps.com Content-Type: application/ld+json Content-Length: 171 ETag: "1382694048000" Expires: 0 {"@context":"http://remotestorage.io/spec/folder-version","items":{"test":{"ETag":"1382694048000","Content-Type":"application/json; charset=UTF-8","Content-Length":106}}} ``` -------------------------------- ### Server Example with 'ws' Module Source: https://github.com/mozilla/readability/blob/main/test/test-pages/lazy-image-1/expected.html A basic server implementation using the 'ws' module to send messages to a Node.js instance for remote CPU profiling control. ```javascript const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); console.log('WebSocket server started on port 8080'); wss.on('connection', (ws) => { console.log('Client connected'); ws.on('message', (message) => { console.log(`Received message => ${message}`); // Example: Trigger CPU profiling on the client instance if (message === 'start-profiling') { // In a real scenario, you'd send a command to the inspector API console.log('Instructing client to start profiling...'); } else if (message === 'stop-profiling') { // In a real scenario, you'd send a command to the inspector API console.log('Instructing client to stop profiling...'); } }); ws.on('close', () => { console.log('Client disconnected'); }); ws.send('Hello from server!'); }); wss.on('error', (error) => { console.error('WebSocket server error:', error); }); ``` -------------------------------- ### Initialize Configuration Module Source: https://github.com/mozilla/readability/blob/main/test/test-pages/qq/source.html Sets up the configuration object for the DC related video module, including cookie settings and video data. ```javascript var n = {}; n.modName = "dc_related_video", n.autoplay_cookie = { key: "aboutVideo_v", domain: ".qq.com", path: "/", expires: 90 }, n.playing_cookie = { key: "dc_vplaying", domain: ".qq.com", path: "/", expires: function() { return new Date((new Date).getTime() + 72e5) } }, n.mini_unmute = { key: "rv_mini_unmute", domain: ".qq.com", path: "/", expires: 1 }, n.qqcomstore = null, n.videos = [], n.automute = !1, window.txPlayer_config = n, i.exports = n ``` -------------------------------- ### OAuth GET Request for Bearer Token Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/expected.html Example of a GET request to an OAuth endpoint to obtain a bearer token for accessing remote storage. Ensure the 'Host' header is correctly set to the server's domain. ```http GET /oauth/michiel?redirect_uri=https%3A%2F%2Fdrinks-unhosted.5\ apps.com%2F&scope=myfavoritedrinks%3Arw&client_id=https%3A%2F%2Fdrinks-\ unhosted.5apps.com&response_type=token HTTP/1.1 Host: 3pp.io ``` -------------------------------- ### Google Tag Manager Data Layer Initialization Source: https://github.com/mozilla/readability/blob/main/test/test-pages/nytimes-3/source.html Initializes the Google Tag Manager data layer with a start timestamp and event. This is a standard setup for integrating with Google Tag Manager. ```javascript (function(w, l) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); })(window, 'dataLayer'); ``` -------------------------------- ### Create Bookmark and Commit Fix (v1) Source: https://github.com/mozilla/readability/blob/main/test/test-pages/mercurial/expected.html Alice creates a bookmark for her work and commits an initial fix. The '(v1)' in the commit message is for tutorial clarity. ```bash $ hg bookmark bug15 $ echo 'fix' > file2 $ hg commit -A -u alice -m 'fix bug 15 (v1)' adding file2 ``` -------------------------------- ### Readability.js with Custom Serializer Option Source: https://context7.com/mozilla/readability/llms.txt This example demonstrates using the `serializer` option with Readability.js to obtain a DOM `Element` instead of an HTML string for `article.content`. This is useful for further processing, such as sanitizing with DOMPurify. Ensure `dompurify` is installed. ```javascript const { Readability } = require('@mozilla/readability'); const { JSDOM } = require('jsdom'); const createDOMPurify = require('dompurify'); const html = `
This content might contain dangerous markup.
Readability strips scripts, but for untrusted input always sanitize the output too.
This content might contain dangerous markup.
..." } ``` -------------------------------- ### Initialize Mercurial Repository Source: https://github.com/mozilla/readability/blob/main/test/test-pages/mercurial/source.html Initializes a new Mercurial repository. This is the first step in setting up a shared project. ```bash $ hg init public ``` -------------------------------- ### WebFinger Response Example Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/expected.html An example of a server's successful response to a WebFinger request. ```http HTTP/1.1 200 OK ``` -------------------------------- ### YUI Environment Setup Source: https://github.com/mozilla/readability/blob/main/test/test-pages/yahoo-3/source.html Initializes a YUI (Yet Another UI) instance and sets up arrays for tracking included modules. This is part of the YUI library's module loading and management system. ```javascript if (!window.YMedia) { var YMedia = YUI(); YMedia.includes = []; YMedia.module_includes = []; } ``` -------------------------------- ### Initialize ClickTale Recorder and Dependencies Source: https://github.com/mozilla/readability/blob/main/test/test-pages/cnn/source.html Sets up the ClickTale recorder, manages script dependencies, and handles readiness callbacks. This code should be included early in the page load. ```javascript var dependencyCallback; var scriptSyncTokens = ["wr"]; var dependencies = scriptSyncTokens.slice(0); var ct2Callback, isRecorderReady; var clickTaleOnReadyList = window.ClickTaleOnReadyList || (window.ClickTaleOnReadyList = []); function isValidToken(token) { if (scriptSyncTokens.indexOf(token) > -1) { var index = dependencies.indexOf(token); if (index > -1) { dependencies.splice(index, 1); return true; } } return false; } clickTaleOnReadyList.push(function() { if (ct2Callback) { ct2Callback(); } isRecorderReady = true; }); window.ClickTaleGlobal = window.ClickTaleGlobal || {}; ClickTaleGlobal.scripts = ClickTaleGlobal.scripts || {}; ClickTaleGlobal.scripts.dependencies = { setDependencies: function(deps) { scriptSyncTokens = deps; }, onDependencyResolved: function(callback) { dependencyCallback = callback; }, notifyScriptLoaded: function(token) { if (isValidToken(token)) { if (dependencies.length === 0 && typeof dependencyCallback === "function") { dependencyCallback(); } } } }; ClickTaleGlobal.scripts.integration = { onReady: function(callback) { if (isRecorderReady) { callback(); } else { ct2Callback = callback; } } }; ``` -------------------------------- ### Request Constructor and Basic Usage Source: https://github.com/mozilla/readability/blob/main/test/test-pages/002/source.html Illustrates how to create a new Request object, including basic GET requests and copying existing requests. ```APIDOC ## Request Constructor ### Description The `Request` interface defines a request to fetch a resource over HTTP. It can be initialized with a URL, and optionally with an options object for method, headers, body, and other attributes. ### Initialization #### Basic GET Request Initialize a `Request` with just a URL. The default method is `GET`. ```javascript var req = new Request("/index.html"); console.log(req.method); // "GET" console.log(req.url); // "http://example.com/index.html" (base URL dependent) ``` #### Copying a Request Create a copy of an existing `Request` object. ```javascript var req = new Request("/index.html"); var copy = new Request(req); console.log(copy.method); // "GET" console.log(copy.url); // "http://example.com/index.html" ``` #### Request with Options Initialize a `Request` with a URL and an options dictionary to specify method, headers, and body. ```javascript var uploadReq = new Request("/uploadImage", { method: "POST", headers: { "Content-Type": "image/png", }, body: "image data" }); ``` ``` -------------------------------- ### UI Ready and Event Binding Source: https://github.com/mozilla/readability/blob/main/test/test-pages/qq/source.html Initializes UI components and sets up event listeners for article sharing and keyboard interactions. Includes delayed execution for image sharing. ```javascript \_MUI.ready(function() { //\_MI.ShareArticle.build('tmblogbt','qqcom.dp.tmblog'); //\_MI.ShareArticle.build('tmblogbt1','qqcom.dp.tmblog1'); //\_MI.ShareArticle.build('MIcblog','qqcom.dp.tmbloghdend'); WBwd("Cnt-Main-Article-QQ"); window.onload = setTimeout(function() { \_MI.ShareArticlePic.build('Cnt-Main-Article-QQ', 'qqcom.dp.sharepic'); }, 1000) }) ``` ```javascript \_MUI.EA(document, 'keydown', function(e) { var isAlt = false, is2 = false, is3 = false, e = \_MUI.E(e); if (e.alt) { isAlt = true } if (e.key == 50) { is2 = true } if (e.key == 51) { is3 = true } if (isAlt & amp; & amp; is2) { document.getElementById('smnav').setAttribute('title', '导航,您可以通过上下键来选择导航'); rwAccess\_2(); } if (isAlt & amp; & amp; is3) { document.getElementById('Cnt-Main-Article-QQ').parentNode.setAttribute('title', '正文,您可以通过上下键来阅读内容'); rwAccess\_3(); } }); ``` -------------------------------- ### GET Request Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/source.html Details the GET request for retrieving a resource, including authentication and optional conditional headers. ```APIDOC ## GET /storage/{user}/{app}/{key} HTTP/1.1 ### Description Retrieves a specific resource from storage. ### Method GET ### Endpoint /storage/{user}/{app}/{key} ### Headers - **Host** (string) - The server host and port. - **Origin** (string) - The origin of the requesting application. - **Authorization** (string) - Bearer token for authentication. - **If-None-Match** (string) - Optional. Used for conditional GET requests. - **Referer** (string) - The referer URL. ### Request Example ```http GET /storage/michiel/myfavoritedrinks/test HTTP/1.1 Host: 3pp.io:4439 Origin: https://drinks-unhosted.5apps.com Authorization: Bearer j2YnGtXjzzzHNjkd1CJxoQubA1o= ``` ``` -------------------------------- ### Initial PUT Request Example Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/expected.html This snippet shows an initial PUT request to create or update a document. It includes necessary headers like Authorization, Content-Type, and Referer. The server may respond with 201 Created or 200 OK. ```http PUT /storage/michiel/myfavoritedrinks/test HTTP/1.1 Host: 3pp.io:4439 Content-Length: 91 Origin: https://drinks-unhosted.5apps.com Authorization: Bearer j2YnGtXjzzzHNjkd1CJxoQubA1o= Content-Type: application/json; charset=UTF-8 Referer: https://drinks-unhosted.5apps.com/? {"name":"test", "updated":true, "@context":"http://remotestorage.io/spec/modules/myfavoritedrinks/drink"} ``` ```http HTTP/1.1 201 Created Access-Control-Allow-Origin: https://drinks-unhosted.5apps.com ETag: "1382694045000" ``` -------------------------------- ### WebFinger Request Example Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/expected.html An example of an in-browser application issuing a WebFinger request using XMLHttpRequest and CORS. ```http GET /.well-known/webfinger?resource=acct:michiel@michielbdejong.com HTTP/1.1 Host: michielbdejong.com ``` -------------------------------- ### Initialize and Play Video Source: https://github.com/mozilla/readability/blob/main/test/test-pages/qq/source.html Initializes a video player instance with specified configuration and plays the video. Handles player creation or retrieval. ```javascript function(t, i, e) { var n = "tvp-mod-player-" + t.vid; return o.setPlayerModId(e), o.setTitle(t.title, t.url), a ? a.play({ vid: t.vid }) : a = new Txplayer({ flashvar: r, useFlashVIPLayer: 0, vid: t.vid, containerId: e, videoType: "vod", width: "100%", height: "100%", playerType: "html5hd", autoplay: i }), a } var o = t("./ui"), r = (t("./config"), { searchbar: 1 }); window.ARTICLE_INFO & amp; & amp; "sports" === window.ARTICLE_INFO.site & amp; & amp; (r.chid = 8); var a; i.exports = n }, { "./config": 1, "./ui": 7 } ``` -------------------------------- ### GET Request for Resource Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/source.html This snippet shows a GET request to retrieve a resource. It includes the Authorization header and optionally an If-None-Match header. ```http GET /storage/michiel/myfavoritedrinks/test HTTP/1.1 Host: 3pp.io:4439 Origin: [https://drinks-unhosted.5apps.com](https://drinks-unhosted.5apps.com) Authorization: Bearer j2YnGtXjzzzHNjkd1CJxoQubA1o= ``` -------------------------------- ### Initialize Comment System Variables Source: https://github.com/mozilla/readability/blob/main/test/test-pages/qq/source.html Sets up variables required for the QQ comment system, including the site identifier, comment ID, group status, and count IDs for displaying comment counts. ```javascript cmt_site = 'tech'; cmt_id = 1576450358; cmt_is_group = 0; cmt_count_id = 'comment_count|comment_count2'; ``` -------------------------------- ### GET Operation for a Specific Document Source: https://github.com/mozilla/readability/blob/main/test/test-pages/ietf-1/expected.html Retrieves a specific document from storage. It supports conditional GET requests using the 'If-None-Match' header. ```APIDOC ## GET /storage/michiel/myfavoritedrinks/test ### Description Retrieves a specific document from the storage. It can be used with an 'If-None-Match' header for conditional requests. ### Method GET ### Endpoint /storage/michiel/myfavoritedrinks/test ### Parameters #### Query Parameters - **If-None-Match** (string) - Optional - A comma-separated list of ETags to check against. ### Response #### Success Response (200 OK) - **Content-Type** (string) - The content type of the response. - **Content-Length** (integer) - The size of the response body. - **ETag** (string) - The ETag of the resource. - **Expires** (string) - Expiration information. #### Response Example ```json HTTP/1.1 200 OK Access-Control-Allow-Origin: https://drinks-unhosted.5apps.com Content-Type: application/json; charset=UTF-8 Content-Length: 106 ETag: "1382694048000" Expires: 0 { "name":"test", "updated":true, "@context":"http://remotestorage.io/spec/modules/myfavoritedrinks/drink" } ``` #### Success Response (304 Not Modified) Returned when the resource has not been modified since the last request (if 'If-None-Match' was used). #### Response Example ```json HTTP/1.1 304 Not Modified Access-Control-Allow-Origin: https://drinks-unhosted.5apps.com ETag: "1382694048000" ``` #### Error Response (404 Not Found) Returned when the requested document does not exist. ``` -------------------------------- ### Creating a Request with Options Source: https://github.com/mozilla/readability/blob/main/test/test-pages/002/expected.html Shows how to create a Request object with custom settings like method, headers, and body. ```APIDOC ## Creating a Request with Options ### Description This example demonstrates creating a `Request` object with specific HTTP method, headers, and a request body. This is commonly used for operations like POST or PUT. ### Method `new Request(url, options)` ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters - **url** (string) - Required - The URL for the request. - **options** (dictionary) - Optional - An object containing request configuration. - **method** (string) - Optional - The HTTP method (e.g., "POST", "PUT"). Defaults to "GET". - **headers** (object) - Optional - An object containing request headers. - **body** (string | Blob | FormData | etc.) - Optional - The request body. ### Request Example ```javascript var uploadReq = new Request("/uploadImage", { method: "POST", headers: { "Content-Type": "image/png", }, body: "image data" }); ``` ### Response N/A (This is a constructor example) ```