Rules Tutorial
A rule is a JSON object that tells Unweb where a site's lists, details, table of contents, and body text are. This tutorial starts with concepts, walks you through your first rule in five minutes, then moves on to a field-by-field reference.
1. Concepts#
1.1 What is a rule#
A rule describes several kinds of pages on a site: search, Discover (categories), detail, table of contents, and content. For each kind of page, it says which address to request and where the content sits on the page. Unweb extracts the content according to the rule and shows it in the native UI.
- A rule is made of declarative extraction expressions (CSS, XPath, JSONPath, regex), and can add restricted JS scripts when needed.
- A rule serves one site only, but it can include several domains of that site.
- Unweb does not bundle or distribute rules for third-party sites. You write rules yourself, or import them from sources you trust.
Only write rules for content you have the right to access, and follow the site's terms of service and robots.txt. Rules cannot be used, and should not be used, to bypass logins, paywalls, DRM, captchas, or rate limits.
1.2 The six content types#
contentType | Used for | Native UI |
|---|---|---|
article | News, blogs, encyclopedias | Article list + article page |
novel | Novels, serials, public-domain books | Detail + table of contents + reader |
manga | Manga | Detail + chapters + image reader |
forum | Forums, discussion boards | Boards + thread list + post page |
video | Video | Detail + sources / episodes + player |
dashboard | Business back-office, ops / sales / OA pages | Dashboard: metric cards, charts, tables, progress, approval steps (4.11) |
1.3 How pages relate#
search / explore(列表) ──点条目──▶ detail(详情) ──▶ toc(目录) ──点章节──▶ content(正文)article and forum can go straight from a list to content, without detail or toc.
dashboard does not follow this chain: it has a single page, pages.board, which extracts one page of data into blocks. It is read-only by default (optional actions and forms are in 4.11), with no search, detail, table of contents or body. Adding the dashboard type and pages.board does not affect existing rules; every field and behavior of the other five types is unchanged.
2. Five-minute start#
2.1 Recommended: start with the site wizard, then edit by hand#
- Open the target site in "Browse" and choose "Analyze this page" from the page menu. Alternatively, in "Me › Rules", tap "New rule" in the top-right menu, then "Analyze site".
- The site wizard detects the site type and generates drafts of the search, list, detail, and other pages. Use "Try on page" to tap elements on the page and fix the selectors.
- After saving, open the rule editor and tap "Test" to run each page and see which fields were extracted and which are empty.
- If something fails, open the "Execution log" to see each step's requests and errors (see Debugging).
Dashboard flow: if the page is a back-office data page (metric cards, charts, tables), choose "Dashboard" in the wizard. The wizard detects the blocks on the page automatically (metric cards, ECharts / Chart.js / Highcharts / ApexCharts charts, <table> tables and so on), turns each detection into a dashboard block, and generates a rule that contains only pages.board. When there are chart blocks it also adds requiresWebView, render and the source.chart capability. You can then edit it by hand in the rule editor; see 4.11.
2.2 A minimal rule#
The rule below has only search and content pages, yet it lets you search Wikipedia in Unweb and read it in the native article page. It uses Wikipedia's public search API.
{
"id": "com.example.my-wiki",
"name": "My Wikipedia",
"version": 1,
"contentType": "article",
"domains": ["wikipedia.org"],
"pages": {
"search": {
"request": {
"url": "https://en.wikipedia.org/w/rest.php/v1/search/page?q={{keyword}}&limit=20",
"responseType": "json"
},
"list": "$.pages[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://en.wikipedia.org/wiki/{{$.key}}",
"summary": "$.description"
}
},
"content": {
"article": {
"title": "css:#firstHeading@text",
"body": "css:#mw-content-text .mw-parser-output@html",
"remove": ["css:.mw-editsection", "css:sup.reference", "css:.navbox"]
}
}
}
}Item by item:
id,name,version,contentType,domains, andpagesare the six required fields.- Writing
wikipedia.orgindomainscoversen.wikipedia.organd all other subdomains. {{keyword}}insearch.request.urlis replaced with the user's input (URL-encoded automatically). The API returns JSON, so write"responseType": "json".listselects each item in the results;fieldsextracts values inside each item.$.titleis a JSONPath.urlusestpl:to build the article address from the API'skey.- The article type needs no detail or toc. Opening an item uses
content.article.bodyfor the body text, andremovestrips edit links, footnote markers, and navigation boxes.
2.3 Import a rule into the app#
Open "Me › Rules", tap "Import..." in the top-right menu, then choose a method:
| Method | Description |
|---|---|
| Paste a link | Enter the http(s) address of the rule file in the input box and tap "Import". The address must return JSON directly, not a web page. |
| Choose files | Pick .json, .txt, .xml, or .webapprule files from "Files", up to 20 at a time, each no larger than 5MB. |
| Paste from clipboard | The clipboard can hold the rule JSON text itself or a link to a rule file. This is the most convenient method for rules generated with AI: copy, then paste. |
| Import link | A link of the form webapp://import?url=... (url is the encoded address of the rule file). When opened, the app first shows the source and downloads only after you confirm. |
Before importing, the app shows which sites the rule covers and whether it contains scripts, and saves it only after you confirm. Rules created in the editor or generated in the site wizard are saved directly. A rule you edit after importing is marked "Modified".
2.4 Testing#
Open a rule, tap "Test", and choose a page type (search asks for a keyword). The result lists the value extracted for each field. Once everything looks right, you can use the rule in "Discover" or with the "Native" button on a web page.
3. File format and top-level fields#
3.1 File envelope#
| Form | Syntax | Description |
|---|---|---|
| Envelope file | {"webappRules": 1, "rules": [ … ]} | One file holding several rules. webappRules can currently only be 1; a larger number prompts you to update the app |
| Single bare object | { "id": …, "contentType": …, "pages": … } | Must contain both pages and contentType |
| Array | [ {…}, {…} ] | Several bare rules |
- Use the extension
.jsonor.webapprule, UTF-8 encoded (a BOM is allowed). - A single rule is limited to 512KB,
scripts.sourceto 256KB, and a single file to 5MB.
3.2 Top-level fields#
Required#
| Field | Type | Constraints and notes |
|---|---|---|
id | string | Regex ^[A-Za-z0-9][A-Za-z0-9._-]{2,127}$ (3-128 characters, case-sensitive). A reverse-domain name is recommended, such as com.example.novel |
name | string | Display name, 1-80 characters, no control characters |
version | integer | 1 to 2147483647. Increase by 1 for every published change |
contentType | enum | video / novel / manga / article / forum |
domains | string array | 1-50 items, no duplicates, see 3.3 |
pages | object | Keys can only be search / explore / detail / toc / content, see section 4 |
Optional#
| Field | Type | Description |
|---|---|---|
author | string | Rule author, at most 80 characters |
urlPatterns | string array | Web address matching. When you browse to a matching address in Web mode, a "Native" button appears in the address bar. At most 50 items, each at most 512 characters. In glob syntax, * matches any characters (including /) and the whole string must match; you can also write a regex with the re: prefix |
iconURL | string | Icon; must start with http(s): or data: |
requiresWebView | boolean | Defaults to false. When true, all pages are loaded like a browser (running the page's own scripts) before extraction, which suits sites whose content is rendered by the front end. Use together with render |
userAgent | string | Custom UA; printable ASCII only, at most 512 characters. When omitted, it matches Web mode |
headers | object | Global request headers, at most 30 items, values at most 2048 characters. Host, Content-Length, and Cookie are forbidden |
rateLimit | object | {"concurrency": 1~6, "intervalMs": 0~10000}: concurrency and request interval per domain. Out-of-range values are clamped with a warning |
scripts | object | JS scripts, see section 7 |
filterExempt | boolean | When true, ad blocking is not enabled when this rule loads pages. Use it only when blocking causes missing content |
verification | object | Characteristics of this site's captcha pages, see 8.1 |
loginDetection | object | Characteristics of this site's login wall, see 8.2 |
readingMode | enum | Manga only: ltr (left to right) / rtl (right to left, Japanese manga) / webtoon (vertical scroll) |
display | object | Native UI appearance, see 9.1 |
requires | string array | Capability declarations, see 9.2 |
Fields not in these two tables are unknown fields: validation gives the warning unknownField, and the app keeps them as is but does not use them. The following fields belong only to your device; they are removed automatically on export and ignored on import, so do not write them into a rule: origin, subscriptionId, isModified, isEnabled, hasScript, scriptConsent, createdAt, updatedAt, sortOrder, syncUUID.
3.3 domains allowlist#
domains is the rule's security boundary. The target host of every page request, redirect, and script request made by the rule must match an entry here, otherwise it is blocked (runtime RUL_006).
| Syntax | Hosts matched |
|---|---|
example.org | example.org and all its subdomains (www.example.org, a.b.example.org) |
*.cdn.example.org | Matches only subdomains of cdn.example.org, not itself |
192.0.2.10, localhost | Exact match |
*, IP-range wildcards, and top-level-domain wildcards (such as*.com) are not allowed.- Writing both
example.comanda.example.comgives the warningdomainCovered: the latter is already covered by the former. - If a site has several domains or mirrors, list them all.
- Image and video addresses themselves are not restricted by
domainsand can come from external CDNs.
4. Page rules pages#
4.1 Which pages each type must define#
| contentType | search / explore | detail | toc | content sub-key |
|---|---|---|---|---|
article | At least one | Optional | Not needed | article |
forum | At least one | Optional | Optional (thread pagination) | thread |
novel | At least one | Required | Required | text |
manga | At least one | Required | Required | image |
video | At least one | Required | Required | video |
dashboard | Not needed | Not needed | Not needed | Not needed; pages.board is required (4.11) |
- A missing page raises the error
missingPage(a dashboard withoutpages.boardtoo); other pages written in a dashboard rule only produce the warningunusedField. Acontentsub-key that does not match the type only produces a warning and has no effect. - A reading page alone is enough: if you only want to turn a certain kind of page into a native view while browsing the web, you can leave out search and explore, but you must write
urlPatterns. Such a rule does not appear in Discover or search and can only be entered from a matching web page; validation gives the warningnoEntryPage. A matched URL opens as a detail page, so novel / manga / video still need detail and toc.
4.2 request#
Every page can have a request. The sections and sectionsFrom of search and explore must have request.url; other pages can omit it, and the defaults are:
| Page | Default request |
|---|---|
| detail | GET {{itemURL}} (the item URL the user opened) |
| toc | The tocURL taken from detail; if there is none, the detail page is reused |
| content | GET {{chapterURL}} (for article / forum entered directly from a list, this is the item URL) |
explore sectionTemplate | GET {{sectionURL}} |
| Field | Description |
|---|---|
url | Request URL template; can use template variables. Must start with http(s):// or {{, and must not contain a username or password. A host that can be determined statically must be in domains (otherwise hostNotDeclared) |
method | GET (default) / POST |
headers | Page-level request headers. Merge order: app defaults < rule headers < page headers < beforeRequest script |
body | A string (up to 64KB, may contain template variables) or an object. An object is form-encoded by default; when headers declares a JSON Content-Type, it is JSON-encoded |
charset | utf-8 / gbk / gb18030 / big5 / shift_jis / euc-jp / euc-kr / iso-8859-1. Detected automatically when omitted. It also determines how {{keyword}} is encoded, so set it for GBK sites |
responseType | html / json / text; inferred automatically when omitted. If an endpoint returns JSON but declares the wrong type, write json explicitly |
timeoutMs | Timeout for this page's request, 5000~60000 ms |
render | Page render-wait parameters, see the next section |
captchaMarkers | Signatures of this site's captcha page (CSS selectors or re: regexes), at most 10 |
render: wait for front-end rendering#
render only takes effect when top-level requiresWebView: true is set, or when this page has a valid capture; otherwise it gives the warning unusedField.
| Field | Range | Description |
|---|---|---|
waitFor | CSS, up to 500 characters | Wait for this selector to appear |
minCount | 1~1000, default 1 | How many elements waitFor must match at least |
quietMs | 0~5000 | How many milliseconds the page must stay unchanged to count as stable (0 means don't wait) |
waitMs | 0~15000, default 0 | Extra time to wait once ready |
timeoutMs | 1000~15000 | Upper limit for waiting. When it is reached, a warning is logged and extraction continues with the current page |
scrollToBottom | Boolean | Scroll to the bottom first to trigger lazy loading |
canvasImages | Boolean, default false | Turn on when the site paints images onto a canvas, see below |
If you are not sure whether to turn on requiresWebView, leave it off at first. If a test run finds that the content can only be fetched by loading the page like a browser, the app tells you the rule needs a WebView and can turn it on with one tap.
Images decrypted in the page#
Some manga sites encrypt their images and only show them after page scripts decrypt them; in developer tools you see blob: addresses or a <canvas>. With requiresWebView on, images that the page has already decrypted and shown are handed to the reader automatically, so images can simply select the rendered <img>. Nothing else is needed.
If the site paints each page onto a canvas (the page has <canvas> but no <img>), add canvasImages: true to render. Each visible canvas (at least 64×64) becomes an image that keeps the original class and id and carries a data-unweb-canvas attribute:
{
"content": {
"request": { "render": { "waitFor": ".reader canvas", "scrollToBottom": true, "waitMs": 800, "canvasImages": true } },
"image": { "images": "css:.reader img[data-unweb-canvas]@src" }
}
}- Only images the page has already decrypted can be handed over. If the site loads images on demand, use
scrollToBottomso the page loads all of them, usewaitFor(withminCount) to wait until they appear, and addwaitMsif needed. - Canvases that the browser’s security rules don’t allow to be read are skipped.
- Up to about 300 images are handled per page. If the images are cleared and you open the chapter again, the reader asks you to reload the chapter; chapters cached for offline reading aren’t affected.
render.capture: use the data the page loads itself#
On some pages, the list is loaded from an endpoint after the page opens. capture makes Unweb open the page normally, take the response that the page loaded itself and whose URL matches as this page's document, and then extract data from it with expressions.
{
"request": {
"url": "https://example.com/list/{{page}}",
"responseType": "json",
"render": { "capture": { "url": "/api/v2/feed*", "index": -1 } }
}
}| Field | Description |
|---|---|
capture.url | Required; a match string, case-sensitive. Without *: substring match against the full URL. With *: wildcard (* can span / and ?), matched against the whole string "path + ? + query". Starting with http(s)://: matched against the full URL |
capture.index | Default -1. Which match to take when there are several: 0 the first, -1 the last |
capture.method | Optional; the request method is compared only when it is written |
- A page with
captureis automatically loaded like a browser; you do not need to setrequiresWebView. - The host of the endpoint does not have to be in
domains, but the host of the page itself must be. - Only text responses in the page's main frame can be captured (each up to 2MB). When nothing matches,
RUL_008is raised, and the execution log lists the requests recorded during this load so you can adjust the match string. - When
scrollToBottom: trueandpagination.mode: "template"are both written and the URL has no page variable, page n is loaded by scrolling down (up to 5 pages). - When
captureis used, write"requires": ["source.intercept"]at the top level, otherwise the warningmissingCapabilityis given.
4.3 pagination#
| Field | Default | Description |
|---|---|---|
mode | none | none: no next page; template: use a page variable in the URL; next: take the "next page" link from the page |
startPage | 1 | Integer ≥ 0: which site page number page 1 corresponds to |
pageSize | — | Integer ≥ 1: items per page, used to compute {{offset}} |
maxPages | 50 | Maximum number of pages to turn. Limit 500 for toc, 200 for others |
nextPageURL | — | Required in next mode. An expression, usually root:css:a.next@href. Stops when it equals the current page or has already been visited |
hasMore | — | An expression; stops when the result is false |
- In
templatemode the URL must contain{{page}},{{page0}}or{{offset}}, otherwise the warningpaginationMismatch;nextmode withoutnextPageURLgives the same warning. - Getting 0 items on page 1 counts as an extraction failure; getting 0 items on a later page counts as "no more".
4.4 pages.search#
| Field | Required | Description |
|---|---|---|
request | Yes | Must have url. Can use {{keyword}}, {{keyword|raw}}, {{page}}, {{page0}}, {{offset}} |
list | Yes | A node expression selecting each result item (do not add a value suffix such as @text) |
fields | Yes | The fields of each item, see the table below |
pagination | No | See 4.3 |
List fields fields (shared by search and explore)#
| Field | Required | Description |
|---|---|---|
title | Yes | Title |
url | Yes* | Item link, automatically made absolute. *Can be omitted when urlAction is configured |
coverURL | No | Cover |
author | No | Author / thread starter |
summary | No | Synopsis, shows at most 500 characters |
latestText | No | Latest chapter, updated-to, reply count, etc. |
tags | No | Tags, multi-valued, at most 20 |
extra | No | Custom key-value pairs {key: expression}, at most 20 entries, key length 1~32 |
urlAction | No | Use when an item has no real link and navigates by click, see 4.10 |
Items missing title or url are dropped; when all items are dropped, RUL_008 is raised. At most 500 items per page.
4.5 pages.explore Discover and categories#
explore can be written in two ways; use either one, or both together (static sections come first when combined).
Option 1: static sections sections#
{
"explore": {
"sections": [
{
"id": "latest", "title": "最新", "group": "栏目",
"request": { "url": "https://example.com/latest?page={{page}}" },
"list": "css:.item",
"fields": { "title": "css:h3@text", "url": "css:a@href" },
"pagination": { "mode": "template" }
}
]
}
}idis required, format^[A-Za-z0-9._-]{1,64}$, and must be unique within a rule (duplicateId).titleis required, 1~80 characters;groupis optional and is used for grouped display.- At most 100 sections. In a forum rule, a section is a "board" and an item is a thread.
Option 2: dynamic sections sectionsFrom + sectionTemplate#
First scrape a category list from some page, then let all categories share one set of list rules:
{
"explore": {
"sectionsFrom": {
"request": { "url": "https://example.com/" },
"list": "css:nav.categories a",
"fields": { "id": "@href | match('/cat/(\\d+)', 1)", "title": "@text", "url": "@href" }
},
"sectionTemplate": {
"request": { "url": "{{sectionURL}}?page={{page}}" },
"list": "css:ul.list > li",
"fields": {
"title": "css:a.title@text",
"url": "css:a.title@href",
"coverURL": "css:img@data-original"
},
"pagination": { "mode": "template" }
}
}
}sectionsFrom.fieldscan haveid,title,url,group,urlAction.titleis required;idandurlare also required, and can be omitted whenurlActionis configured.{{sectionURL}}is the section'surl; whensectionTemplate.requestis omitted, it requests this.- Extraction in
sectionsFromdoes not supportjs:scripts; writing one raisesRUL_012.
Filter blocks filters#
Many category pages have filter rows such as "Type / Year / Region" at the top. filters extracts these options from the same response as the list page; when the user taps an option, the app uses its link as the new list URL.
{
"filters": [
{
"id": "genre", "title": "类型", "parent": "sections",
"list": "css:.filter-row:nth-of-type(1) a",
"fields": { "title": "@text", "url": "@href", "selected": "@class | match('active')" }
},
{ "id": "year", "title": "年份", "list": "css:.filter-row:nth-of-type(2) a" }
]
}| Field | Description |
|---|---|
id | Required, format ^[A-Za-z0-9_-]{1,40}$, must be unique. sections and items are reserved names |
title | Display name; defaults to id |
parent | Parent block: sections (top-level sections) or the id of another filter block |
list | Required; the option nodes |
fields.title / fields.url | Default to @text and @href respectively |
fields.selected | Selected if the result is non-empty and not false / 0. When omitted, the item whose link equals the current request URL is selected |
filters is written inside pages.explore and requires sections or sectionTemplate. At most 200 items per block, extracted only on page 1; options whose links are not within domains cannot be tapped. It is recommended to write "requires": ["explore.filters"] at the top level.
4.6 pages.detail#
| Field | Description |
|---|---|
request | Defaults to GET {{itemURL}} |
fields | Required, and title is required in it. Available: url, coverURL, author, summary, latestText, tags (same as in lists; filled from the list item's value when not extracted), plus intro (full synopsis, often used with html2text), status (the original serialization-status text), updatedAtText (update time), extra (up to 20 entries), readingMode (manga only) |
statusMap | Status mapping {"original text": "ongoing" / "completed" / "unknown"} |
readingModeMap | Manga only: reading-direction mapping, e.g. {"日漫": "rtl"} |
tocURL | An expression. When the table of contents is on another page, extracts the URL of that page |
blocks | Extra blocks on the detail page, see below |
Without statusMap, the app recognizes common keywords: 连载 / 連載 / ongoing / serializing mean ongoing; 完结 / 完結 / 完本 / completed / finished / end mean completed. When a video rule opens a detail page it also fetches the table of contents, to show lines and episodes.
Detail page blocks blocks#
Used for related recommendations, author / genre links, long text paragraphs and so on; shown only on the detail pages of novel / manga / video. At most 12 blocks, and at most 60 items per block; it is recommended to write "requires": ["detail.blocks"] at the top level.
| Field | Description |
|---|---|
id | Required, format ^[A-Za-z0-9_-]{1,40}$. The reserved names sections, items, toc, lines, intro, tags cannot be used, and the id must not duplicate a filters id |
title | Block title |
role | Required. items: a list of work cards, needs list and fields.title / fields.url; links: tag-style links, needs list; text: a piece of text, needs value |
open | links only: the id of the static section to open on tap, or write @template to apply sectionTemplate. When nothing matches, it opens in the browser |
lines | text only: the number of lines shown when collapsed, 1~50 |
{
"blocks": [
{
"id": "related", "title": "相关作品", "role": "items",
"list": "css:.related li",
"fields": { "title": "css:a@text", "url": "css:a@href", "coverURL": "css:img@src" }
},
{ "id": "about", "title": "作者简介", "role": "text", "value": "css:.author-bio@text", "lines": 4 }
]
}4.7 pages.toc Table of contents#
Plain table of contents#
{
"toc": {
"list": "css:#list dd",
"fields": { "title": "css:a@text", "url": "css:a@href", "isLocked": "css:.vip | exists" },
"skip": "css:.volume-title | exists",
"reverse": false,
"pagination": { "mode": "next", "nextPageURL": "root:css:a.next@href" }
}
}| Field | Description |
|---|---|
list + fields.title + fields.url | Required. Duplicate urls within the same line keep only the first |
fields.isLocked | Whether payment / membership is required; a boolean expression. Used only for display marking |
skip | A boolean expression evaluated for each node; nodes where it is true (such as volume-title rows) are skipped |
reverse | When true, reverses the whole table of contents (use when the site lists newest first) |
pagination | Multi-page tables of contents are merged page by page; maxPages limit is 500 |
Line structure (video)#
A video's "lines + episodes" structure uses lines instead of list:
{
"toc": {
"lines": {
"names": "css:.line-tabs li@text",
"groups": "css:.line-groups > ul",
"episodes": { "list": "css:li a", "fields": { "title": "@text", "url": "@href" } }
}
}
}names (line names, multi-valued) and groups (the container node of each line) are paired one to one in order; episodes extracts the episodes inside each container. At most 20000 chapters; RUL_008 is raised when the result is 0 items. When the content page itself carries an episode list, it can also be written in pages.content.toc (same structure, no separate request).
4.8 pages.content Body#
content.request defaults to GET {{chapterURL}}. Write the sub-key that matches the contentType.
content.article (article)#
| Field | Description |
|---|---|
body | Required, the body container, usually css:article@html |
title / author / publishedAtText | Title, author, publish time |
remove | An array of selectors for nodes to delete, such as ads and share bars, at most 50 |
The body HTML is converted into native blocks such as paragraphs, headings, images, quotes, lists and code; scripts, styles, forms and similar elements are removed automatically. Audio and video in article bodies and forum posts also become native controls: <video> plays in place with the built-in player (16:9, playback speed, Picture in Picture, and seamless switch to full screen), <audio> renders as an audio bar (with background playback), <iframe> embeds from supported platforms (YouTube, Bilibili, Vimeo, Tencent Video and others) load in place, and custom elements can also carry a data-unweb-media JSON attribute.
When a site uses custom player tags or puts the real media URL inside an inline <script> in the page source, rewrite it into a standard <video> or <audio> tag in a parse / transform script without turning on requiresWebView. Image, audio and video requests carry the article URL as Referer by default and merge top-level headers; for large or throttled article pages with heavy inline scripts, set content.request.timeoutMs to 30000–45000.
content.text (novel)#
| Field | Description |
|---|---|
paragraphs | Required, the paragraphs, multi-valued. For example css:#content p@text, or css:#content@html | html2text | lines |
title | Chapter title |
remove | An array of content to delete, at most 50. Selectors act on the page; re: regexes act on each paragraph's text |
nextPageURL | Next page within the chapter |
autoMerge | Default true: automatically fetch and merge the following pages (up to 10 pages) |
replace | Cleanup replacements [{"pattern": "…", "replacement": "", "regex": true}], at most 100, executed in order. An entry with an invalid regex is ignored and gives the warning invalidRegex |
content.image (manga)#
| Field | Description |
|---|---|
images | Required, image URLs, multi-valued, data: allowed |
width / height | Optional, used for pre-layout |
nextPageURL / pagination | Use when one chapter is split into several pages |
Image requests carry Referer: chapter URL and the rule's headers by default.
content.thread (forum)#
| Field | Description |
|---|---|
posts.list | Required, the floor (post) nodes |
posts.fields | floor, author, body are required (body is the post text and is converted into body blocks); avatarURL, timeText, quote are optional |
title | Thread title |
pageCount | Total number of pages |
nextPageURL / pagination | Page turning |
authorOnlyURL | "Thread starter only": a URL template (can use {{url}} for the thread URL), or an extraction expression |
content.video (video)#
| Field | Description |
|---|---|
streams | Required, video URLs. Either one expression (each value produces one stream), or an array [{"url": expression, "type": expression, "quality": expression}]. type is 'hls', 'mp4' or 'other', inferred from the extension when omitted |
subtitles | Optional, subtitles [{"url", "language", "label"}]; the format (vtt / srt / ass) is inferred from the extension |
{
"content": {
"video": {
"streams": [{ "url": "css:video source@src", "quality": "'auto'" }],
"subtitles": [{ "url": "css:video track@src", "language": "css:video track@srclang", "label": "css:video track@label" }]
}
}
}Playback uses the same Referer and User-Agent as the web page. Write rules only for videos that the page offers publicly and that you have the right to watch; protected videos can only be played in the web page.
4.9 Automatic URL completion#
URL-type fields (url, coverURL, nextPageURL, tocURL, images, videos, subtitles, avatars) are automatically made absolute, so you don't need to write absurl by hand:
- The final page URL (after redirects) is the base; if the page has
<base href>, that takes precedence. //host/pathbecomeshttps:;/path,path,?qand../xare all resolved by the standard rules.- Empty values,
javascript:,blob:and the like are dropped;data:is kept only in image-type fields (cover, manga images, avatar).
4.10 urlAction: items that navigate by click#
In some single-page apps, items have no href and navigate through click events. In that case you can add the following to the list fields (or sectionsFrom.fields):
{ "fields": { "title": "@text", "urlAction": { "event": "click", "target": "a.topic" } } }event:clickortouch, required.target: the child element to click inside the item (CSS); when omitted, the item itself is clicked.urlActiontakes effect only when no realurlcan be obtained: the app replays the click on the page to get the URL it navigates to.- When using
urlAction,listmust be CSS or XPath.
4.11 pages.board dashboards#
Turns one page of data from a business web system (a sales board, OA approvals, a subscription analytics console, an inventory page...) into a native dashboard: metric cards, charts, tables, progress bars, approval steps, item lists and text. The rule type is contentType: "dashboard" and it uses only pages.board; no search / explore / detail / toc / content. Dashboards are read-only by default: tapping an item opens the original page in the in-app browser. To approve or submit forms right inside the dashboard, use actions and forms below (write actions, each with a native confirmation).
Dashboard rules take no part in search and never reach the bookshelf. Once a dashboard rule is installed, Discover gets a "Dashboard" category at the end. For pages that need a login, use requiresWebView + render; the hidden browser renders them with your signed-in session (see 4.2).
{
"pages": {
"board": {
"request": { "url": "https://ops.example.com/sales.html", "render": { "waitFor": "#kpis .kpi-card" } },
"title": "css:h1@text",
"filters": [ ],
"blocks": [ ]
}
}
}| Field | Description |
|---|---|
request | Same as 4.2. The default dashboard URL; required when the rule has no urlPatterns. Both render and render.capture work |
title | An extraction expression for the dashboard title; the rule name is shown if it yields nothing |
filters | Time range, department and similar filters, written like explore.filters (filter blocks). Picking one reloads the whole page from that item's URL, which must be inside domains |
blocks | Required, at least one, shown in order, at most 24 (extras are ignored with the warning clamped) |
Common block fields#
| Field | Description |
|---|---|
id | Required, ^[A-Za-z0-9_-]{1,40}$, unique within the dashboard. It must not equal a filters id (both share the keys of display.blocks) or a reserved id: sections items toc lines intro tags |
title | Block title, 1-80 characters; defaults to id |
role | Required: metrics / series / table / progress / steps / items / text |
source | Where the data comes from. Default = this page's document; chart:... = a chart-library instance in the rendered page (see chart sources) |
from | "table": table / series read an HTML <table> directly, with automatic header and numeric-column detection |
list | An extraction expression; each node = one metric / row / item. With from: "table" it selects the table (default css:table, the first one) |
fields | The fields each role uses, see below |
columns | [{title, value, numeric?}]: the columns of a table, or a wide-format series (one series per column); at most 30 |
value | text role only: the text expression |
unit | A block-level unit for metrics / series (¥, %, orders); fields.unit wins |
states | steps only: {state: substring}, extra "raw text to state" mapping |
A block that extracts nothing is simply not shown and is not an error. One failing block (a failed expression, a missing required field) drops only that block. Only when every block is empty do you get the error RUL_008, which usually means the login expired or the page changed.
The seven roles#
| Role | Required | Optional | Notes |
|---|---|---|---|
metrics metric cards | fields.label, fields.value | delta trend unit higherIsBetter url | One card per node; without list a single metric is read from the whole page. delta = the change text; trend = a sparkline (several values, a JSON array, or numbers separated by whitespace / , / ;, up to 120 points); higherIsBetter = false / 0 / no means "lower is better". Up to 24 |
series charts | One of: from: "table"; columns + fields.label; fields.label + fields.value; source: "chart:..." | fields.series unit | from: "table": the first non-numeric column is the category and every other numeric column becomes a series; a footer total row is left out. Wide format: one row per category, one series per column. label + value: paired by index into points, fields.series names the series, same names merge. Up to 20 series x 500 points |
table tables | from: "table"; or list + columns | fields.url | With columns, one row per node; numeric is detected when omitted. fields.url = the row link. Up to 30 columns x 500 rows; from: "table" keeps the <tfoot> total row |
progress | fields.label, fields.value | total text | value accepts 68 / 100, 68 of 100, ¥912,000 / ¥1,200,000 and 68%; total overrides; with no total and a value above 1 it is read as a percentage. text defaults to the raw value. Up to 60 |
steps | list | fields.title (default @text) subtitle state | An approval flow; state reads a status word or @class and is classified as done / current / pending / rejected. Up to 60 |
items | list, fields.title, fields.url | coverURL author summary latestText tags | URLs must be inside domains; they open in the in-app browser. Up to 60 |
text | value | - | All values, blanks dropped, joined with newlines; up to 20,000 characters |
How steps states are recognized: your states are checked first (keys can only be done current pending rejected; each value is a case-insensitive substring list separated by |, e.g. "current": "process|doing"), then the built-in keywords, in the order rejected, current, done, pending; if nothing matches the step is pending. Built-ins include reject denied fail, current active processing, done complete approved and pending wait todo (plus Chinese equivalents).
How number text is parsed#
Metrics, progress, numeric table columns and chart values all share one parser, so you do not need to clean values in the rule.
| Case | Rule | Example |
|---|---|---|
| Number and unit | Takes the first number and drops thousands separators; parentheses or a leading - make it negative; suffixes 亿 万 千 K M B multiply; the unit is a currency symbol before the number, else %, else the first word after the number | ¥12,480 = 12480, unit ¥; 3.2万 = 32000; (1,234) = -1234 |
delta | With %: divided by 100, and a direction word sets the sign (↓ ▼ down negative, ↑ ▲ up positive, parentheses negative). Without %: only a bare number is accepted (treated as already a ratio) | +12.5% = 0.125; ↓3% = -0.03; +12 orders is not recognized |
| Progress | a / b, a of b = done a, total b; 68% = 0.68 | ¥912,000 / ¥1,200,000 |
| Numeric column | A cell parses as a number, has only a currency symbol / sign / parenthesis before it and at most 3 non-digit characters after it; a column is numeric when at least 60% of its non-empty cells are | 2026-11-20, Q1 and 12 orders are not numbers |
Chart sources: chart:#
Many admin consoles draw charts with ECharts / Chart.js / Highcharts / ApexCharts, so the DOM holds only a <canvas>. A role: "series" block can read the chart's data directly through source, with no image parsing.
| Form | Meaning |
|---|---|
chart:echarts#0 | The 0th ECharts chart in DOM order. Library names: echarts highcharts chartjs apexcharts; the index starts at 0 and defaults to 0 |
chart:auto#1 | The 1st chart across all libraries together, in DOM order |
chart:css(#c-region) | The chart whose container sits inside (or contains) an element matched by that CSS selector; an optional #index may follow. Use it when the chart order on the page can change; it is more stable than an index |
- Rendering is required: the rule needs
requiresWebView: trueand the dashboard request must not userender.capture(that returns API JSON, and the page's chart objects are not there). Otherwise the block fails and validation warnsneedsRendering(V-40). - The app reads the chart data once the page is ready. Pages often fetch data after load, so it waits up to 4 seconds, with an overall 8-second timeout and at most 40 charts.
source: "chart:..."works only onseriesblocks;list/fields/columns/fromon such a block are ignored, while the blockunitstill applies.- If the n-th chart does not exist, the block is not shown (this is not a failure).
- Combo charts (revenue bars plus a target line) keep every series, each drawn in its own type. The chart title comes from the library, else from the nearest heading above the chart.
Display: display.blocks and span#
How a block is shown goes in display.blocks.<block id> (declare display.blocks in requires). Besides show / fallback / hidden, dashboards add span.
| Role | show values | Default |
|---|---|---|
series | column stackedColumn bar stackedBar line area pie donut | The kind suggested by the chart source; otherwise line above 12 categories, else column |
metrics | grid (cards), row (one swipeable row) | grid |
table | table | table |
progress | bar, ring | bar |
steps | vertical, horizontal | vertical |
items | list, rail, grid | list |
text | text | text |
span is full (a whole row) or half (half width in the two-column layout on tablets and wide screens; always a full row on phones). By default pie / donut charts and ring progress are half and everything else is full. If show is not valid for the role, fallback is tried, then the default; hidden: true hides the block.
Actions: actions / itemActions (write actions)#
A dashboard can write: approve / reject, comment, edit, submit a form. actions (block level, any role) appear as buttons on the block; itemActions (item level, only for items / table) give every item / row its own set of buttons. Before any action that changes data, the app always shows a native confirmation, and a rule cannot turn it off. How it runs: the hidden browser opens the site page with your login, fills in values and clicks the page's own button like a person would (or calls a page function, or sends a request), then uses the page's own text as the success / failure message. Only dashboards (dashboard) support actions for now.
{
"id": "todo", "title": "Awaiting my approval", "role": "items", "list": "css:#pending .apw",
"fields": { "title": "css:a.card .t@ownText", "url": "css:a.card@href", "key": "@data-id" },
"itemActions": [
{ "id": "approve", "title": "Approve", "style": "primary",
"run": { "scope": "row", "steps": [ { "acceptDialog": true }, { "click": "button.btn-approve" } ] },
"success": { "text": ".toast.success" }, "error": "#alert .alert.error" }
]
}| Field | Description |
|---|---|
id | Required, [A-Za-z0-9_-]{1,40}, unique within the block |
title | Button text, 1-40 characters (optional for a form's submit) |
style | primary / normal (default) / destructive (the confirmation is shown in red) |
icon | An SF Symbol name |
confirm | Confirmation text, up to 300 characters; the app's default wording if omitted |
mutates | Default true (forced confirmation, needs authorization); false = a read-only action (export, refresh) that is not confirmed |
inputs | Items the user fills in before running, up to 20 |
run | Required; exactly one of steps / js / request |
success | {text?, gone?, url?, json?}; any one that holds means success |
error | CSS: any new visible text there means failure, and that text is shown as the message |
after | On success: refresh (default, reload the dashboard) / open (open the result page) / none |
timeout | Milliseconds to wait for a success / failure signal, 1000-60000, default 15000 |
At most 8 actions per block. Inputs inputs[] (the same structure as a form block's fields[]): id (required), label, kind (text multiline number date datetime select multiselect toggle file password; an unknown value is treated as text), required, placeholder, options ([{value, title}] or an array of strings), value (prefill), min / max, help, selector (form blocks: the element to fill). Files are limited to 10 MB and can only be used with upload.
The three ways to run: run#
| Form | Description |
|---|---|
{ "page"?, "scope"?, "steps": [...] } | Prefer this one. Opens the page in the hidden browser and operates the page's existing controls step by step |
{ "page"?, "js": "functionName" } | After opening the page, calls the function f(inputs, ctx) from scripts.source in the page's own world, so it can use the page's JS; it returns {ok?, message?, openURL?}, and throwing means failure. Needs script authorization |
{ "page"?, "request": {method, url, headers?, body?, json?, csrf?, csrfHeader?} } | After opening the page, sends a request directly with the page's login (cookies). csrf = a CSS selector that reads the token; a string body is form-encoded, an object / array is JSON; success = 2xx and (success.json holds, or when absent the response JSON's ok / success is not false); method is GET POST PUT PATCH DELETE, default POST |
Page to run on: run.page (a template), then the form block's page, then the item URL, then the dashboard URL. With "scope": "row" on an item action (or when the item has no URL), the app first finds that row on the dashboard page and the step selectors are relative to that row; a step with "scope": "page" is relative to the whole page (dialogs, global messages). If the row cannot be found you get "the item is no longer on the page". Items are located by fields.key (for example "key": "@data-id") or by the item URL, so write a key whenever you write itemActions.
Template variables (usable in page, request.url, headers, body and a step's value): {{inputs.<id>}}, {{item.url}}, {{item.key}}, {{board.url}}, {{page.url}}, {{csrf}}. Referring to an input you did not declare is an error.
| Step | Description |
|---|---|
{"fill": css, "from": inputId} or "value": template | Sets an input's value (works for React / Vue controlled inputs too); writes text into contenteditable |
{"select": css, "from" / "value"} | A <select> is matched by value, then by text; radio / checkbox groups select the matching item |
{"check": css, "from" / "value"} | Sets a checkbox to that boolean (default true) |
{"upload": css, "from": inputId} | Puts the file into an <input type=file> |
{"click": css} | Scrolls into view and clicks; fails if the browser's own form validation rejects, with that field's message |
{"waitFor": css | "navigation", "timeout": ms} | Waits for an element to appear / for the main page to finish navigating (default 10 s) |
{"acceptDialog": true} | Afterwards the page's confirm() / prompt() answer yes (the default is no); alert text is kept as a fallback message |
{"wait": ms} | Pause, up to 30000 |
Each step has one verb; the rest are options: from / value / timeout / optional / scope. When an element is missing, element steps retry every 250 ms until the step's timeout (default 5000, up to 30000); with "optional": true the step is skipped, otherwise it fails. At most 40 steps.
Deciding success: success.text is a CSS selector (a visible element with text means success and its text becomes the message) or re:<regex> (matches the page text); success.gone: the selector no longer matches; success.url: a regex matched against the address after navigation; success.json (request only): simple conditions such as $.ok == true or $.code != 0. error is checked first (text that was already there before the run does not count), then the success conditions, every 200 ms until timeout; a timeout is a failure. Always write both success and error: without them the app can only wait for the page to settle and call it success when no new error appears, so a silent rejection by the site goes unnoticed.
Forms: the form block#
role: "form" shows a native form that is submitted on the site. Declare board.forms in requires.
{
"id": "expense", "title": "Expense request", "role": "form", "from": "form", "list": "css:form#expense",
"submit": { "id": "submit", "title": "Submit request", "success": { "url": "approval\\.html\\?id=" },
"error": "#form-error", "after": "open" }
}from: "form"(or nofields): reads the first<form>selected bylist(defaultcss:form).text/email/telbecome text,textareamultiline,number/rangenumber,date/datetime-localdate / datetime,selecta choice (multiplea multi-choice),checkboxa toggle, same-nameradioone choice,filea file,passworda password. Labels come from<label>/aria-label/placeholder, current page values prefill, up to 20 fields.- Explicit
fields: [...](an array): each item givesid,kind,labeland aselectorpointing at the page element. submit: by default the title is the page's submit button text and the style isprimary. Withoutrunthe app opens the form page, re-reads the form, fills the fields that were given values by type, and clicks the submit button. A missing required field is reported locally without opening the page. Withrun.stepsyour own steps are used (fromreferences field ids).pagesets the page that holds the form (default: the dashboard page).
Embedded pages: the embed block#
role: "embed" places a piece of web content in a dashboard card; declare board.embed. There are two kinds: html (a web template that ships with the rule) and fragment (a region of a site page, using the site login).
{
"id": "stats", "title": "Approval stats", "role": "embed", "embed": "html", "height": 220, "scripts": true,
"html": "<b id=n>0</b><script>n.textContent=[].concat(unweb.data.types||[]).length</script>",
"data": { "types": "css:#pending .apw .meta span:nth-child(2)@text" }
}{ "id": "flow", "title": "Approval progress", "role": "embed", "embed": "fragment",
"url": "/approval.html?id=AP-1040", "selector": "ol.steps", "height": 260 }| Field | Description |
|---|---|
html | The template, up to 200 KB. {{name}} = the first value of name in data, HTML-escaped; {{{name}}} = all values joined by newlines and sanitized with an allowlist (script / style / iframe / event attributes / javascript: links removed); {{json:name}} = a JSON array that is safe inside <script>. Site content is never injected raw |
data | {name: expression}, evaluated on the dashboard page; read it in the page via window.unweb.data (one value = a string, several = an array, none = null) |
url / selector | fragment: the page address (default: the dashboard page; relative addresses resolve against the dashboard page and must be inside domains) and the region to cut out; it uses the site login |
height | Initial height (pt), 40-2000, then adapts to the content |
scripts | html defaults to false (no scripts run); fragment defaults to true (the site's own scripts, which single-page apps need to render). true on html = the rule ships its own JS and needs script authorization |
interactive | Default true; false = view only, touches go to the outer scroll view |
Inside an embedded page (an html block with scripts authorized) the bridge window.unweb is available: open(url) opens in the in-app browser (must be inside domains), refresh() reloads the dashboard, toast(text) shows a message, action(id, inputs) triggers one of this rule's actions (it still goes through the native confirmation), data (read-only), theme (the current theme) and holdScroll(bool) (pause the outer scroll while dragging). The theme is provided as CSS variables that follow light / dark mode: --ui-bg --ui-surface --ui-surface2 --ui-fill --ui-text --ui-text2 --ui-text3 --ui-accent --ui-on-accent --ui-separator --ui-success --ui-warning --ui-danger --ui-font --ui-font-serif --ui-font-mono --ui-radius.
Limits: the embedded page's CSP allows only inline scripts (once authorized) and scripts from the rule's domains; network requests (connect) can reach only domains; subframes and form submission are always blocked; images / media / fonts may use https. A dashboard keeps at most 4 live embeds at once and loads them lazily as they scroll near.
Safety and authorization for write actions#
- A rule with write actions (
mutatesnotfalse), a form block,run.js, or an html embed withscripts: trueneeds the same one-time authorization as a script. The consent sheet adds a line saying the rule can use your login to submit forms, approve or change data on the site, and that every change is asked about first. Until authorized the rule is unusable, and validation reports the infowriteActions. - Every run has a native confirmation; a rule can neither disable it nor run automatically. The pages, requests and redirects involved must be inside
domains. - Logs record only input ids, never values; passwords and files appear as
***. One action runs at a time per rule, and a failed action is never retried automatically. - The site wizard's "Try it" shows the dashboard only and never runs actions. The wizard recognizes approve / reject buttons next to items and
<form>s, and you can add an action by tapping a button on the page; page-level buttons it finds are off by default. - Never invent selectors: use only selectors you have confirmed exist on the page. If the site changes and a selector stops matching, the action fails with "no ... on the page" instead of doing something wrong.
Capabilities, validation and limits#
- Declare
"requires": ["board.blocks"]when you usepages.board.blocks, add"board.actions"foractions/itemActions,"board.forms"for form blocks,"board.embed"for embed blocks,"source.chart"forchart:sources and"display.blocks"fordisplay.blocks. - Results are cached for 60 seconds; pull-to-refresh skips the cache. Validation codes are in 10.1.
Common pitfalls#
- A chart block is empty:
requiresWebView: trueis missing, the request usesrender.capture, or the page is slower thanwaitFor. PointwaitForat an element that only appears once the data is in (such as a table row). - Index-based chart picking is fragile: when the chart order can change, use
chart:css(selector). - Numbers read as text: a cell with extra words (such as
12 orders) is not numeric. Set"numeric": trueon the column or pick a node that holds only the number. - delta shows no direction: without
%only a bare number is accepted; extract the text that carries the%. - An action does nothing, or a failure looks like success:
success/errorare missing; the selector is outside the row (item actions need"scope": "row", and elements inside a dialog need"scope": "page"); the page shows a confirm box and there is noacceptDialog; the block has nofields.key. - Everything empty (
RUL_008): the login expired and you were redirected, or the page changed. Sign in again and re-check with Test. - All steps are pending: use
"state": "@class"when the state lives in the class, and addstatesif the site uses its own words. from: "table"works only on HTML documents; for API JSON uselist+columns.
5. Extraction expression syntax#
5.1 Structure#
分支 || 分支 || … ← 回退:依次尝试,取第一个非空结果
分支 = [root:] 来源 | 过滤器 | 过滤器 … [##正则##替换]
或 tpl:文本{{子表达式}}文本… ← 拼接5.2 Sources#
| Syntax | Meaning | Example |
|---|---|---|
css:selector@value | CSS selector (css: can be omitted) | css:h3 a@text, img@data-src |
@value | Read a value from the current node itself (common inside list items) | @href, @text |
xpath:…, or starting with / or ( | XPath 1.0 | //meta[@property='og:title']/@content |
json:…, or starting with $. or $[ | JSONPath | $.data.list[*].name |
re:/regex/flags#group | Regex extraction | re:/"title":"(.*?)"/#1 |
'text' or "text" | Constant | 'ongoing' |
{{variable}} | Template variable | {{keyword}} |
js:functionName | Call a script function | js:decodeTitle |
root: prefix | Ignore the current list item and evaluate against the whole document | root:css:a.next@href |
5.3 CSS accessors#
| Syntax | Result |
|---|---|
@text | Text of all descendants (whitespace collapsed). Used by default when no accessor is given |
@ownText / @textNodes | Only the text directly owned by the element itself |
@html | Inner HTML |
@outerHtml / @all | HTML including the element itself |
@bg | Background image URL, see 5.9 |
@attributeName | Read an attribute, such as @href, @data-src, @content. Attribute names may contain only letters, digits, _, : and - |
- When a selector contains several
@characters, the last one outside brackets and quotes is the separator, soa[href*="@"]@hrefworks fine. - Do not give
listfields an accessor; they need a node collection. - When list items are JSON objects,
@keyreads that key's value directly.
CSS extensions#
- Pseudo-classes:
:contains(text),:containsOwn(text),:matches(regex),:has(…),:not(…),:eq(n),:lt(n),:gt(n),:nth-child, and so on. - Wildcard classes:
.ssrcss-*-Titlematches class names with a random hash such asssrcss-1x2y3z-Title;.*means any class. - AMP pages: if a selector containing
i-amphtml-matches nothing, the AMP runtime class names are stripped automatically and it is tried once more.
5.4 XPath#
Works only on HTML / XML. On a JSON response the result is empty and a warning is logged. The XPath union operator | must be wrapped in parentheses, for example (//a | //b); otherwise it is treated as a filter separator.
5.5 JSONPath#
| Syntax | Description |
|---|---|
$ | Root |
.key, ['key'] | Read a key |
[n] | Index; negative values are supported ([-1] is the last) |
[*], .* | Wildcard |
..key | Recursive search |
[?(@.k == 'v')] | Simple filter; operators == != < > <= >=; the key may be a dotted path such as @.a.b |
Slices [1:3], multi-select ['a','b'] and script expressions are not supported. A list of $.data.list is expanded automatically into one item per element, and child fields such as $.title are evaluated relative to each element.
5.6 Regex source re:/…/#
- Optional flags are
i,m,sandx.#ntakes the n-th capture group; if omitted, group 1 is used when the pattern has capture groups, otherwise the whole match. - Only the first match is used. Inside a list item the regex runs against that item's outerHTML; outside a list item it runs against the whole raw response.
- A literal
/in the regex must be written as\/. Input over 1MB is not processed and the result is empty. re:can also be used as a filter:css:script@html | re:/id=(\d+)/#1.
5.7 Filters#
Filters are chained in order with |, and names are case-sensitive. String arguments must be quoted; integer arguments are not.
| Filter | Effect | Example |
|---|---|---|
trim / lower / upper | Trim whitespace / lowercase / uppercase | @text | upper |
replace('regex','replacement'[,'flags']) | Replace all matches; the replacement may use $1 | replace('^Author:\s*', '') |
replaceFirst('regex','replacement') | Replace only the first match | |
match('regex'[, group]) | Take the given group of the first match (group 1 by default). If nothing matches, the value is dropped | @href | match('/book/(\d+)', 1) |
split('separator') / join('separator') | Split into multiple values / join into one | split(',') |
first / last / index(n) / slice(a[,b]) | First, last, n-th, or a range. Zero-based; negative numbers count from the end | index(-2), slice(0,3) |
prepend('s') / append('s') | Add a prefix / suffix | |
default('s') | Use s when the result is empty | default('Unknown') |
absurl | Convert to an absolute URL (done automatically for URL fields) | |
int | Take the first integer | css:.count@text | int |
lines | Split on line breaks into multiple values and drop empty lines | @html | html2text | lines |
unique | Remove duplicates, keeping order | |
exists | Outputs "true" / "false", for boolean fields | css:.vip | exists |
html2text | Turns <br> and <p> into line breaks, strips tags, decodes entities | @html | html2text |
decodeEntities / urlDecode | Decode HTML entities / percent-encoding | |
js:functionName | Call a script function | @text | js:fix |
re:/…/#n | Regex extraction |
first, last, index, slice and exists keep the node form, so their result can still be used as a list; other filters convert nodes to text.
5.8 Fallback, concatenation, replace shorthand#
| Feature | Syntax | Notes |
|---|---|---|
| Fallback | img@data-src || img@src | The right side is evaluated only if the left side is empty |
| Default value | css:.status@text | default('unknown') | |
| Concatenation | tpl:https://example.com/book/{{@data-id}}.html | Each {{ }} is evaluated independently; an empty result becomes an empty string |
| Replace shorthand | css:.author@text##^Author:\s*## | Equivalent to | replace(…); must be at the end of the branch. Ending with ### replaces only the first match; write a literal # as \# |
What "empty" means: a selector with no match, a missing attribute, a value that is all whitespace, and an attribute that exists but is an empty string all count as empty, and trigger || fallback and default.
5.9 Background images and lazy loading#
@bglooks in this order:background(-image): url(…)in the inlinestyle; the attributesdata-bg,data-background,data-bg-src,data-background-image,data-original,data-src; then rules in the page's stylesheets that match the element.<img>has no automatic lazy-load handling:img@srcis not swapped fordata-src, so write the fallback yourself:css:img@data-src || css:img@data-original || css:img@src.
5.10 Common pitfalls#
- Backslashes must be doubled in JSON:
\din an expression becomes"\\d"in a JSON string, and\[becomes"\\[". - A top-level
|is always a filter separator. Only a|inside quotes,(),[],{{ }}orre:/…/does not count. - No filters after
tpl:: intpl:a{{x}} | trim, the| trimis treated as plain text. To process the result, put the filter inside{{ }}. - A misspelled variable name in
tpl:raises no error: for example{{keywrod}}is treated as a CSS tag selector and silently returns empty. matchdrops the value when nothing matches, which can leave the whole field empty. Add| default('…')as a safety net.- A wrong CSS selector raises no error: at runtime only a warning is logged and the result is empty. Syntax errors in filter names, brackets, quotes and so on are reported by validation as
exprSyntax, with the character position. - An expression is 1 to 4096 characters long; a single field's result over 64KB is truncated (summary and body text have higher limits).
6. Template variables#
| Variable | Where available | Description |
|---|---|---|
{{keyword}} | search | The keyword the user typed, percent-encoded in URLs according to charset |
{{keyword|raw}} | search | As typed, not encoded |
{{page}} / {{page0}} / {{offset}} | Pagination | Page number (starting from startPage) / page number − 1 / (page number − 1) × pageSize |
{{sectionId}} / {{sectionURL}} | explore | The current section's id / URL |
{{itemURL}} | detail, toc | Work URL |
{{chapterURL}} | content | Chapter URL |
{{url}} | authorOnlyURL | Post URL |
{{host}} | All | The first non-wildcard domain in domains |
{{baseURL}} | All | The current base URL |
{{storage.key}} | All | A value from script storage (requires a script and authorization); empty string if the key does not exist |
{{js:functionName}} | request.url only | Calls a script function with no arguments and substitutes its return value into the URL |
- An unknown variable or an unclosed
{{inrequest.urlor a string-formrequest.bodymakes validation reportinvalidURL. {{js:…}}is evaluated only inrequest.url: inheadersit is not substituted, and inbodyit yields an empty string. For dynamic headers or a dynamic body, use abeforeRequestscript.
7. JS scripts#
When declarative expressions are not enough (for example the response is encoded or its structure needs reshaping), you can write JS scripts. Avoid them when you can: a rule without scripts works immediately after import and is easier to maintain.
7.1 Where scripts go#
{
"scripts": {
"source": "function prepare(req, ctx) { return req; }\nfunction decode(resp, ctx) { return resp; }",
"hooks": {
"search": { "beforeRequest": "prepare" },
"content": { "afterResponse": "decode" }
},
"fieldTimeoutMs": 3000,
"hookTimeoutMs": 10000
}
}- All functions go in
scripts.source(at most 256KB) and must be top-levelfunctionorasync functiondeclarations. A top-levelconst f = () => …will not be found. - Referencing a function that does not exist makes validation report
missingFunction; a syntax error is reported asscriptSyntax. - The keys of
hooksaresearch,explore,detail,tocandcontent. fieldTimeoutMs(field functions, default 3000) andhookTimeoutMs(page hooks, default 10000) can each be set to 100 to 30000.
7.2 Field-level functions#
- As a source:
"title": "js:fn"; the argumentvalueis the current node's outerHTML, ornullwhen there is no node. - As a filter:
"title": "css:a@text | js:fn"; the argumentvalueis the result of the previous step:null, a string, or an array of strings. - Signature
fn(value, ctx); return a string, an array, ornull(meaning empty).ctxholds no node; to parse HTML, usedom.parse(value)inside the function.
7.3 Page-level hooks#
| hook | Signature | Purpose and conventions |
|---|---|---|
beforeRequest | (req, ctx) → req | Rewrite the request, for example to add headers or parameters. req = {url, method, headers, body}. The returned headers replaces the original headers as a whole, so modify req.headers and return the whole object |
afterResponse | (resp, ctx) → resp | Decode or rewrite the response. resp = {status, url, headers, body}. Only status and body of the return value are used; if body is returned as an object it is treated as JSON |
parse | (resp, ctx) → result object | Takes over parsing completely, replacing declarative extraction |
transform | (output, ctx) → result object | Post-process the result of declarative extraction. Must return a complete object; for example, search must return {items, …} |
Result format of parse / transform#
| Page | Format |
|---|---|
| search / explore | {items: [{title, url, coverURL?, author?, summary?, latestText?, tags?}], nextPageURL?, hasMore?} |
| detail | {title, coverURL?, author?, intro?, status?, tags?, extra?, tocURL?, …} |
| toc | {chapters: [{title, url, isLocked?}], nextPageURL?, hasMore?}; for video use {lines: [{name, episodes: [...]}]} |
| content · novel | {title?, paragraphs: [...], nextPageURL?} |
| content · manga | {images: [url]} or {pages: [{url, width?, height?}]} |
| content · video | {streams: [{url, type?, quality?}], subtitles?} |
| content · article | {title, author?, publishedAtText?, html} |
| content · forum | {title, posts: [{floor?, author, avatarURL?, timeText?, quote?, html}], pageCount?} |
Fields of the wrong type are dropped and a warning is written; URLs are completed automatically.
The ctx object#
| Field | Description |
|---|---|
rule | {id, name, version, domains} |
step | The current page: search / explore / detail / toc / content |
env | Runtime environment: jsc (default environment) or webview (page environment) |
url / baseURL | Request URL / final URL |
page | Page number |
keyword | Keyword (search) |
sectionId | Section id (explore) |
itemURL | Work URL |
chapter | The current chapter object (content) |
doc | The current document. In the default environment it exists only in afterResponse / parse / transform; in the page environment it is the page's document |
7.4 Runtime environments#
| Condition | Environment | Characteristics |
|---|---|---|
requiresWebView: false (default) | Default environment (ctx.env is jsc) | No DOM, fetch, XMLHttpRequest or timers; only the APIs below are available. An async function can await only those APIs |
requiresWebView: true | Page environment (ctx.env is webview) | Can read the page's document; the page's own scripts cannot see your script |
Globals are not guaranteed to persist between pages; use storage for data that must be kept. Avoid infinite loops and Promises that never settle: a timeout reports RUL_010, and after repeated timeouts the rule's scripts are paused for the rest of the current session.
7.5 Available APIs#
http#
http.get(url, opts?) // → Promise<{status, url, headers, body}>
http.post(url, body, opts?)
http.getSync(url, opts?) // 同步版本,仅默认环境可用
http.postSync(url, body, opts?)
// opts: { headers?, charset?, timeoutMs?(5000~60000), responseType?: 'text' | 'json' | 'base64' }- The target host must be in
domains, and so must any redirect target. Relative URLs are allowed and resolve against the current page. - A non-2xx response does not reject; check
statusyourself. - Requests automatically carry the site's cookies from the app, the rule's UA and
headers. - At most 20 requests per page step, and a response body of at most 5MB.
- When a captcha is encountered, even if you catch the exception with
try/catch, the step still ends as "verification required", and the user completes the verification in the web page.
cookie (read-only, only for URLs within domains)#
await cookie.get(url) // → {name: value}
await cookie.get(url, name) // → string | nullstorage (the rule's private on-device key-value store)#
await storage.get(key) // 不存在时为 null
await storage.set(key, value) // value 需能被 JSON 序列化
await storage.remove(key)
await storage.keys()
await storage.clear()All these methods return a Promise. Keys are 1 to 128 characters, a single value is at most 64KB once serialized, and each rule may store at most 1MB in total. Storage is on this device only and is not synced.
log / console#
log.debug / info / warn / error(...), and console.log / info / debug / warn / error. Output appears in the execution log, at most 4KB per entry and 500 entries per step.
util#
| Function | Description |
|---|---|
base64Encode(s, enc?) / base64Decode(s, as?, charset?) | Base64 encode / decode |
hexEncode / hexDecode | Hex encode / decode |
md5 / sha1 / sha256(text) | Digests, returned as lowercase hex |
hmacSHA256(key, msg, keyEncoding?) | Returns hex |
aesEncrypt(p) / aesDecrypt(p) | p = {data, key, iv?, mode: 'CBC' | 'ECB' | 'GCM', padding?, keyEncoding?, dataEncoding?, output?, tag?}. Key of 16/24/32 bytes; iv of 16 bytes for CBC and 12 bytes for GCM; GCM decryption must pass tag |
absURL(base, rel) | Resolve a URL |
urlEncode(s, charset?) / urlDecode(s, charset?) | Supports charsets such as gbk and big5 |
jsonPath(obj, path) | Returns an array. Not available in the page environment |
decodeCharset(base64Bytes, charset) | Decode bytes with the given charset |
util in the page environment supports only the utf-8 and latin1 charsets.
dom (HTML up to 5MB)#
const d = dom.parse(html, baseURL?);
d.select('css') / d.selectOne('css') / d.xpath('expr')
el.text() / el.ownText() / el.html() / el.outerHtml() / el.attr(name) / el.absURL(attr)
d.eval('css:h1@text') // 用第 5 节的表达式语法取值;页面环境不可用7.6 Security limits and script authorization#
- Scripts can access only the domains in
domains. They cannot read other sites' cookies, nor reach personal data such as files, location or the clipboard. - Authorization: a rule containing scripts that is imported from a file, link or clipboard starts in the "pending authorization" state. Until the user reviews the scripts in the rule details and taps "Allow", pages that use scripts report
RUL_012, while pages without scripts work as usual. If the scripts ordomainschange in an update, authorization is requested again. Rules you save yourself in the editor count as authorized. - "Contains scripts" is decided by the app automatically:
scripts.sourceis non-empty, or any expression containsjs:.
7.7 Examples#
Add headers before the request, decode after the response, tidy after extraction#
{
"scripts": {
"source": "function addLang(req, ctx) {\n req.headers['Accept-Language'] = 'en';\n return req;\n}\nfunction decode(resp, ctx) {\n resp.body = util.base64Decode(resp.body);\n return resp;\n}\nfunction tidy(out, ctx) {\n out.items = out.items.map(function (i) { i.title = i.title.trim(); return i; });\n return out;\n}",
"hooks": { "search": { "beforeRequest": "addLang", "afterResponse": "decode", "transform": "tidy" } }
}
}Parse a JSON API with parse (complete rule)#
This rule demonstrates {{js:…}} and parse. Note: even when parse is used, the search list / fields are still required by validation.
{
"id": "com.example.hn-parse-demo",
"name": "HN (parse demo)",
"version": 1,
"contentType": "forum",
"domains": ["hn.algolia.com"],
"rateLimit": {"concurrency": 1, "intervalMs": 500},
"pages": {
"search": {
"request": {
"url": "https://hn.algolia.com/api/v1/search?query={{keyword}}&tags={{js:tag}}&page={{page0}}"
},
"list": "$.hits[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://hn.algolia.com/api/v1/items/{{$.objectID}}"
},
"pagination": {"mode": "template", "maxPages": 5}
},
"content": {
"request": {"responseType": "json"},
"thread": {
"title": "$.title",
"posts": {
"list": "$..children[*]",
"fields": {
"floor": "$.floor",
"author": "$.author",
"timeText": "$.created_at",
"body": "$.text"
}
}
}
}
},
"scripts": {
"source": "function tag() { return 'story'; }\nfunction parseHits(resp, ctx) {\n var d = JSON.parse(resp.body);\n return {\n items: d.hits.map(function (h) {\n return {\n title: h.title,\n url: 'https://hn.algolia.com/api/v1/items/' + h.objectID,\n author: h.author,\n latestText: h.num_comments + ' comments'\n };\n }),\n hasMore: d.page + 1 < d.nbPages\n };\n}",
"hooks": {"search": {"parse": "parseHits"}}
}
}8. Captcha and login detection#
8.1 verification: captcha detection#
The app recognizes common captcha pages. When one appears, it shows the site's own verification page for the user to complete personally, then continues automatically; the app never completes or bypasses a captcha itself. If a site's verification page is unusual and the app does not recognize it, you can add the following signals:
| Field | Description |
|---|---|
statusCodes | Extra status codes treated as a verification signal (must be combined with other conditions); at most 10 entries, values 100 to 599 |
bodyContains | The page is judged to be a captcha page if the response body contains any of these strings; at most 10 entries |
selectorExists | Judged if the page contains any of these CSS selectors; at most 10 entries |
urlContains | Judged if the final URL contains any of these strings; at most 10 entries |
successSelector / successURLPattern / successCookie | Conditions that show the user has completed verification: a selector appears / the URL matches a regex / a given cookie appears |
stableMs | Settling period after completion, 500 to 5000 ms |
disableBuiltInDetection | Boolean; turns off the app's built-in weak-signal detection (use it for false positives) |
The page-level request.captchaMarkers works the same way but applies only to that page.
8.2 loginDetection: login detection#
When any condition is met, the user is told that login is required (RUL_LOGIN_REQUIRED). After the user logs in in Web mode, Native pages use the same login state.
| Field | Description |
|---|---|
statusCodes | Status codes |
urlContains | Final URL contains |
bodyContains | Response body contains |
selectorExists | Page contains selector |
loginURL | The address opened by "Log in on the web"; its host should be in domains |
When loginDetection is not configured, the app prompts for login only in clear-cut cases: HTTP 401, or a redirect to a page whose path contains login / signin / passport while the required fields are empty.
{
"loginDetection": {
"urlContains": ["/account/login"],
"selectorExists": ["form#login-form"],
"loginURL": "https://example.com/account/login"
}
}9. Appearance display and capability declaration requires#
9.1 display: native interface appearance#
display is optional; the app picks a default appearance based on the content type. Invalid values are ignored without an error. Adjust it visually in the "Appearance" step of the site wizard, then look at the generated JSON.
| Path | Allowed values | Description |
|---|---|---|
list.style | poster / book / story / text / card | List style: poster wall / book cover / image-and-text feed / plain text / card |
list.columns | 2~4 | poster style only |
list.coverAspect | 3:4 / 2:3 / 16:9 / 1:1 | Cover aspect ratio |
list.thumbnail | leading / trailing | Thumbnail position for the story style |
list.featured | Boolean | Enlarge the first item into a featured card |
list.density | comfortable / compact | Spacing |
list.titleLines / list.summaryLines | 1~3 / 1~4 | Number of lines shown for title and summary |
list.slots | author / summary / latest / tags / x.<extra key> | Which fields appear on the card, in order |
list.latestBadge | Boolean | Show the latest chapter as a badge on the cover |
sections | {section id: list config} | Override the list style per section |
category.style | tabs / grouped / grid | Category navigation style |
detail | header (cover / immersive), introLines (1~8), showTags, showStatus, tocInline (integer >= 0; 0 means only a "Contents" button), primaryLabel (primary button label) | Detail page |
toc | style(list / grid), descending | Table of contents |
blocks | {block id: {…}} | How filter blocks, detail blocks and dashboard blocks are displayed and where; best generated by the wizard. span (full / half) is for dashboard blocks only (4.11) |
immersive | Boolean, default false | Full screen on scroll: native pages hide the status bar, top buttons and bottom action bar while you scroll down, and bring them back when you scroll up, reach the top or tap the top of the screen. Has no effect when the content fits on one screen; novel and manga readers keep their own immersive mode. The “Full screen on scroll” switch on the rule’s detail page changes it too |
{
"display": {
"list": { "style": "story", "thumbnail": "trailing", "density": "compact", "slots": ["author", "summary"] },
"detail": { "header": "cover", "introLines": 4 },
"toc": { "style": "list", "descending": false }
}
}9.2 requires: capability declaration#
When a rule uses a newer capability, declare it in requires. An app version that does not recognize a capability skips that feature and keeps working normally, instead of failing to import.
| Capability | Declare it when you use |
|---|---|
explore.filters | pages.explore.filters |
detail.blocks | pages.detail.blocks |
source.intercept | request.render.capture |
display.blocks | display.blocks |
board.blocks | pages.board.blocks (dashboards) |
source.chart | A dashboard block uses source: "chart:..." |
board.actions | A dashboard block uses actions / itemActions |
board.forms | A dashboard uses a role: "form" block |
board.embed | A dashboard uses a role: "embed" block |
Using capture, detail.blocks, board.blocks, source.chart, board.actions, board.forms or board.embed without declaring it gives the warning missingCapability; an unknown capability name gives the warning unknownCapability.
10. Validation and error codes#
10.1 Validation (on save or import)#
A rule with an error cannot be enabled; a rule with only warnings can be saved and used. Every issue includes its location (a JSON path), and expression errors also include the character position.
Common errors#
| code | Meaning |
|---|---|
required | A required field is missing, has the wrong type, or the JSON itself is invalid |
invalidId / invalidValue | Malformed id / invalid value (enum, length, range) |
invalidDomain | domains is empty, has more than 50 entries, has duplicates, or contains an invalid host name |
hostNotDeclared | The request URL's host is not in domains |
invalidURL | The request URL does not start with http(s) or {{, contains a username and password, or has an invalid template variable |
invalidHeader | Invalid request header, or a forbidden header was used |
invalidPattern | urlPatterns is invalid |
exprSyntax | Expression syntax error (with character position) |
missingFunction / scriptSyntax | Script function does not exist / script syntax error |
missingPage | A required page or content sub-key is missing; or there is neither search / explore nor urlPatterns |
duplicateId | Duplicate id for a section, filter block, detail block or dashboard block |
tooLarge / formatTooNew | Rule or script too large / file format version is newer than the app supports |
Common warnings#
unknownField (unknown field), clamped (value out of range was clamped), unusedField (the field has no effect, for example render written without WebView enabled, or readingMode in a non-manga rule), paginationMismatch (inconsistent pagination config), invalidRegex (invalid regex in a cleanup replacement), domainCovered (domain already covered), noEntryPage (no search / Discover entry; the rule can only be entered from a matching web page), unknownCapability / missingCapability (unknown capability name / missing capability declaration).
Dashboard validation#
| Code | Level | Meaning |
|---|---|---|
| V-38 | error | Missing pages.board; blocks missing / not an array / empty; request.url missing when there is no urlPatterns; a block id missing / malformed / reserved / duplicate / clashing with a filter; role missing; a role's required field missing (see the seven roles); a column without title or value |
| V-39 | warning | More than 24 blocks / 30 columns; unknown role; a malformed source or unknown library; chart: on a non-series block; fields, columns, states, value or list on a role that does not use them; from other than table; a states key that is not one of the four state names; pages.board in a non-dashboard rule; requires missing board.blocks / source.chart |
| V-40 | warning (needsRendering) | A chart: source is used, but the rule lacks requiresWebView: true or the dashboard request uses render.capture |
| V-41 | error | Actions (actions / itemActions / a form's submit): actions not an array; id missing / malformed / duplicated in the block; title missing (except submit); run missing, or not exactly one of steps / js / request; steps empty or over 40, an unknown verb, several verbs in one step, a missing selector for fill / select / check / upload / click, fill / select / upload with neither from nor value, waitFor without a value; from or {{inputs.x}} referencing an undeclared input; run.js not a function name or absent from scripts.source; request.url missing, an invalid method, a static host outside domains; malformed success.json / success.text / success.url; after not refresh / open / none; an input id missing / malformed / duplicated |
| V-42 | warning | More than 8 actions / 20 inputs; itemActions outside items / table; scope: "row" on a block-level action; from / value on a step that takes no value; success.json on a non-request run; an unknown input kind, a select without options, an unknown style, an unknown template variable; a selector the parser cannot read (invalidSelector, which may still work in a browser, so only a notice); a step timeout or timeout out of range |
| V-43 | error | A form block with neither fields nor from: "form" / list; an explicit field without selector; an embed block without embed or not html / fragment; html missing html or over 200 KB; data not an object, an illegal name or a bad expression; a fragment without selector or with a static url host outside domains; a non-numeric height |
| V-44 | warning / info | Keys that do not apply on form / embed blocks (url / selector on html, html / data on fragment); an html template naming something not in data; height outside 40-2000; requires missing board.actions / board.forms / board.embed. A rule with write actions / a form / run.js / an html embed with scripts gets the info writeActions: it needs one-time authorization |
10.2 Runtime error codes#
When a rule fails at runtime, the page shows an explanation and an error code.
| Code | Meaning | What to do |
|---|---|---|
RUL_001 | Rule unavailable (deleted, disabled, or format too new) | Check that the rule is enabled |
RUL_002 | Invalid rule structure or URL | See the validation report |
RUL_003 | The rule does not define this page | Add the missing page |
RUL_004 | Network failure | Check your connection and retry later |
RUL_005 | The site returned an HTTP error | 429 means too many requests; increase rateLimit.intervalMs |
RUL_006 | A domain that was not declared was accessed | Add the domain to domains |
RUL_007 | Expression syntax error | Fix it according to the validation report |
RUL_008 | The page opens, but no content can be extracted | The selector is broken, or the content is rendered client-side (check whether WebView is suggested) |
RUL_009 | The script threw an exception | Check the function name and stack in the log |
RUL_010 / RUL_011 / RUL_013 / RUL_014 / RUL_016 | Timeout or resource limit exceeded | Reduce the number of requests and the amount of data, then retry later |
RUL_012 | Script not authorized | Check and allow the script in the rule details |
RUL_015 | Page encoding not recognized | Set request.charset |
RUL_017 | The imported content is not recognized as a rule | Make sure it is Unweb rule JSON and that the link does not return a web page |
RUL_020 | Rule format version too new | Update the app |
RUL_021 | The search keyword is empty | Enter a keyword before searching |
RUL_CAPTCHA_REQUIRED | Captcha / human verification required | Complete the verification in the web page as prompted |
RUL_LOGIN_REQUIRED | Login required | Log in in Web mode |
11. Debugging in the app#
- Test (trial run): tap "Test" in the rule editor to run each page in turn. The result lists the extracted value of every field, plus the raw response and a page snapshot. A trial run does not require the rule to be enabled and does not change its state.
- Execution log: every run is recorded; open it to see three tabs:
- Steps: a summary of input and output, timing, and errors for each step (request, render, each hook, list selection, and so on);
- Requests: method, URL, status code, size, and timing of each request, including requests made by scripts;
- Log: for example which fields are empty, why items were dropped, and the output of
login scripts.
- In a script, print intermediate values with
log.info(JSON.stringify(x)). - "Copy all" copies the whole log so you can share it. Sensitive values such as Cookie and Authorization are automatically replaced with
***. - Picking selectors: after turning on developer mode in "Me › Developer tools", the page menu of a web page offers panels such as Elements, Source, and Network for inspecting the page structure directly. You can also connect the iPhone to a Mac and use Safari's Web Inspector.
Suggested order: first check that the request succeeded (status code, final URL); then check that list selects the right number of nodes; finally go through the fields to see which is empty. Most problems are a selector at the wrong level (fields should be relative to each list item) or content that is actually rendered client-side.
12. Complete examples#
The first four rules below are the examples built into the app (a few fields are trimmed for readability); the fifth is a fictional dashboard example. All of them pass validation and can be imported and modified directly.
12.1 article: Wikipedia#
Search uses the public MediaWiki API; the detail page and body are parsed from HTML. remove strips edit links, footnotes, navigation boxes, and everything after the "References" section. The \\\\[ in replace becomes \\[ after JSON decoding, and is decoded once more in the expression's string argument, giving the regex \[.
{
"id": "org.wikipedia.sample",
"name": "Wikipedia",
"version": 2,
"author": "Unweb",
"contentType": "article",
"domains": ["wikipedia.org", "wikimedia.org"],
"urlPatterns": ["https://*.wikipedia.org/wiki/*"],
"iconURL": "https://en.wikipedia.org/static/favicon/wikipedia.ico",
"requiresWebView": false,
"rateLimit": {"concurrency": 2, "intervalMs": 200},
"pages": {
"search": {
"request": {
"url": "https://en.wikipedia.org/w/rest.php/v1/search/page?q={{keyword}}&limit=20",
"responseType": "json"
},
"list": "$.pages[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://en.wikipedia.org/wiki/{{$.key}}",
"coverURL": "$.thumbnail.url",
"summary": "$.description || $.excerpt | html2text"
},
"pagination": {"mode": "none"}
},
"detail": {
"fields": {
"title": "css:#firstHeading@text",
"coverURL": "css:meta[property='og:image']@content",
"summary": "css:meta[property='og:description']@content || css:#mw-content-text .mw-parser-output > section:first-child > p:not(.mw-empty-elt)@text | first | replace('\\\\[[0-9a-z ]+\\\\]', '')",
"intro": "css:meta[property='og:description']@content || css:#mw-content-text .mw-parser-output > section:first-child > p:not(.mw-empty-elt)@text | first | replace('\\\\[[0-9a-z ]+\\\\]', '')"
}
},
"content": {
"article": {
"title": "css:#firstHeading@text",
"publishedAtText": "css:#footer-info-lastmod@text",
"body": "css:#mw-content-text .mw-parser-output@html",
"remove": [
"css:.mw-editsection", "css:sup.reference", "css:.reference",
"css:.reflist", "css:.mw-references-wrap", "css:.navbox",
"css:.hatnote", "css:.ambox", "css:.metadata", "css:.mw-empty-elt",
"css:style", "css:.mw-heading:has(#Notes) ~ *",
"css:.mw-heading:has(#Notes)",
"css:.mw-heading:has(#References) ~ *",
"css:.mw-heading:has(#See_also) ~ *",
"css:.mw-heading:has(#External_links) ~ *",
"css:.mw-heading:has(#Further_reading) ~ *",
"css:.mw-heading:has(#References)",
"css:.mw-heading:has(#See_also)",
"css:.mw-heading:has(#External_links)",
"css:.mw-heading:has(#Further_reading)"
]
}
}
}
}12.2 article: Wikinews#
Same structure as Wikipedia. incategory:"Published" (encoded) is appended to the search keyword, so only published news is searched.
{
"id": "org.wikinews.sample",
"name": "Wikinews",
"version": 2,
"author": "Unweb",
"contentType": "article",
"domains": ["wikinews.org", "wikimedia.org"],
"urlPatterns": ["https://*.wikinews.org/wiki/*"],
"iconURL": "https://en.wikinews.org/static/favicon/wikinews.ico",
"requiresWebView": false,
"rateLimit": {"concurrency": 2, "intervalMs": 200},
"pages": {
"search": {
"request": {
"url": "https://en.wikinews.org/w/rest.php/v1/search/page?q={{keyword}}%20incategory%3A%22Published%22&limit=20",
"responseType": "json"
},
"list": "$.pages[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://en.wikinews.org/wiki/{{$.key}}",
"coverURL": "$.thumbnail.url",
"summary": "$.excerpt | html2text"
},
"pagination": {"mode": "none"}
},
"detail": {
"fields": {
"title": "css:#firstHeading@text",
"coverURL": "css:meta[property='og:image']@content",
"summary": "css:meta[property='og:description']@content || css:meta[name=description]@content || css:#mw-content-text .mw-parser-output p:not(.mw-empty-elt)@text | first",
"intro": "css:meta[property='og:description']@content || css:meta[name=description]@content || css:#mw-content-text .mw-parser-output p:not(.mw-empty-elt)@text | first"
}
},
"content": {
"article": {
"title": "css:#firstHeading@text",
"publishedAtText": "css:#footer-info-lastmod@text",
"body": "css:#mw-content-text .mw-parser-output@html",
"remove": [
"css:.mw-editsection", "css:.noprint", "css:.navbox",
"css:.xambox", "css:.mw-collapsible", "css:.hatnote",
"css:.metadata", "css:.mw-empty-elt", "css:style",
"css:.mw-heading:has(#External_links) ~ *",
"css:.mw-heading:has(#External_links)"
]
}
}
}
}12.3 forum: Hacker News#
Everything uses the public Hacker News Search API. explore.sections defines two sections; {{page0}} maps to the API's zero-based page number; $..children[*] recursively collects all replies as floors.
{
"id": "com.ycombinator.hn.sample",
"name": "Hacker News",
"version": 1,
"author": "Unweb",
"contentType": "forum",
"domains": ["hn.algolia.com"],
"urlPatterns": ["https://hn.algolia.com/api/v1/items/*"],
"iconURL": "https://news.ycombinator.com/favicon.ico",
"requiresWebView": false,
"rateLimit": {"concurrency": 2, "intervalMs": 300},
"pages": {
"search": {
"request": {
"url": "https://hn.algolia.com/api/v1/search?query={{keyword}}&tags=story&hitsPerPage=20&page={{page0}}",
"responseType": "json"
},
"list": "$.hits[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://hn.algolia.com/api/v1/items/{{$.objectID}}",
"author": "$.author",
"latestText": "tpl:{{$.num_comments}} comments",
"summary": "$.url"
},
"pagination": {"mode": "template", "startPage": 1, "maxPages": 10}
},
"explore": {
"sections": [
{
"id": "front",
"title": "Front page",
"request": {
"url": "https://hn.algolia.com/api/v1/search?tags=front_page&hitsPerPage=30",
"responseType": "json"
},
"list": "$.hits[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://hn.algolia.com/api/v1/items/{{$.objectID}}",
"author": "$.author",
"latestText": "tpl:{{$.num_comments}} comments",
"summary": "$.url"
},
"pagination": {"mode": "none"}
},
{
"id": "ask",
"title": "Ask HN",
"request": {
"url": "https://hn.algolia.com/api/v1/search?tags=ask_hn&hitsPerPage=30",
"responseType": "json"
},
"list": "$.hits[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://hn.algolia.com/api/v1/items/{{$.objectID}}",
"author": "$.author",
"latestText": "tpl:{{$.num_comments}} comments"
},
"pagination": {"mode": "none"}
}
]
},
"detail": {
"request": {"responseType": "json"},
"fields": {
"title": "$.title",
"author": "$.author",
"intro": "$.text | html2text || $.url"
}
},
"content": {
"request": {"responseType": "json"},
"thread": {
"title": "$.title",
"posts": {
"list": "$..children[*]",
"fields": {
"floor": "$.floor",
"author": "$.author",
"timeText": "$.created_at",
"body": "$.text"
}
}
}
}
}
}12.4 novel: Wikisource#
A novel needs detail, toc, and content.text. The table of contents selects only links containing /Chapter; the body is split into paragraphs with @html | html2text | lines.
{
"id": "org.wikisource.sample",
"name": "Wikisource",
"version": 2,
"author": "Unweb",
"contentType": "novel",
"domains": ["wikisource.org", "wikimedia.org"],
"urlPatterns": ["https://en.wikisource.org/wiki/*"],
"iconURL": "https://en.wikisource.org/static/favicon/wikisource.ico",
"requiresWebView": false,
"rateLimit": {"concurrency": 2, "intervalMs": 200},
"pages": {
"search": {
"request": {
"url": "https://en.wikisource.org/w/rest.php/v1/search/page?q={{keyword}}%20incategory%3A%22Novels%22&limit=20",
"responseType": "json"
},
"list": "$.pages[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://en.wikisource.org/wiki/{{$.key}}",
"coverURL": "$.thumbnail.url",
"summary": "$.description || $.excerpt | html2text"
},
"pagination": {"mode": "none"}
},
"detail": {
"fields": {
"title": "css:#firstHeading@text",
"coverURL": "css:meta[property='og:image']@content",
"author": "css:#ws-author@text || css:#header_author_text a@text",
"intro": "css:meta[property='og:description']@content || tpl:{{css:#firstHeading@text}} · Wikisource"
}
},
"toc": {
"list": "css:table.ws-summary a[href*='/Chapter']",
"fields": {"title": "@text", "url": "@href"}
},
"content": {
"text": {
"title": "css:#firstHeading@text",
"paragraphs": "css:.prp-pages-output@html | html2text | lines",
"remove": [
"css:.pagenum", "css:.mw-editsection", "css:style",
"css:section[data-mw-section-id='-1'] > h2"
]
}
}
}
}12.5 dashboard: sales board#
A fictional site, ops.example.com, showing the structure; it is not a built-in example. A rendered back-office page: metric cards, two ECharts charts (a monthly revenue + target combo chart and a regional share donut), a table read straight from <table>, an orders table with custom columns, quota progress and a "Time range" filter. Chart blocks use chart:echarts#n to pick the n-th chart on the page, so the rule needs requiresWebView: true and the source.chart capability. region becomes a half-width donut in display.blocks and quota is shown as ring progress.
{
"id": "com.example.ops.sales",
"name": "Example Ops Board",
"version": 1,
"contentType": "dashboard",
"domains": ["ops.example.com"],
"requiresWebView": true,
"requires": ["board.blocks", "display.blocks", "source.chart"],
"pages": {
"board": {
"request": {
"url": "https://ops.example.com/sales.html?range=30d",
"render": {"waitFor": "#kpis .kpi-card", "timeoutMs": 15000}
},
"title": "css:h1@text",
"filters": [
{
"id": "range",
"title": "Time range",
"list": "css:#range a",
"fields": {"selected": "@class | match('is-selected')"}
}
],
"blocks": [
{
"id": "kpi",
"title": "Key metrics",
"role": "metrics",
"list": "css:#kpis .kpi-card",
"fields": {
"label": "css:.kpi-label@text",
"value": "css:.kpi-value@text",
"delta": "css:.kpi-delta@text",
"trend": "css:svg.sp@data-points"
}
},
{
"id": "revenue",
"title": "Monthly revenue vs target",
"role": "series",
"source": "chart:echarts#0"
},
{
"id": "region",
"title": "Sales by region",
"role": "series",
"source": "chart:echarts#1"
},
{
"id": "top",
"title": "Top products",
"role": "table",
"from": "table",
"list": "css:table#top"
},
{
"id": "orders",
"title": "Latest orders",
"role": "table",
"list": "css:.order-row",
"columns": [
{"title": "Order no.", "value": "css:.no@text"},
{"title": "Amount", "value": "css:.amt@text", "numeric": true}
],
"fields": {"url": "css:a@href"}
},
{
"id": "quota",
"title": "Quota attainment",
"role": "progress",
"list": "css:.quota",
"fields": {
"label": "css:.name@text",
"value": "css:.done@text",
"total": "css:.target@text"
}
}
]
}
},
"display": {
"defaults": 1,
"blocks": {"region": {"show": "donut", "span": "half"}, "quota": {"show": "ring"}}
}
}A second example, a detail page with only steps: the approval flow is shown horizontally, and urlPatterns lets the app offer native mode when you browse a matching page.
{
"id": "com.example.ops.approval",
"name": "Example Approval Detail",
"version": 1,
"contentType": "dashboard",
"domains": ["ops.example.com"],
"requiresWebView": true,
"requires": ["board.blocks", "display.blocks"],
"urlPatterns": ["https://ops.example.com/approval.html*"],
"pages": {
"board": {
"request": {
"url": "https://ops.example.com/approval.html?id=AP-1040",
"render": {"waitFor": "#steps .step", "timeoutMs": 15000}
},
"title": "css:h1@ownText",
"blocks": [
{
"id": "flow",
"title": "Approval flow",
"role": "steps",
"list": "css:ol.steps li",
"fields": {
"title": "@ownText",
"subtitle": "css:small@text",
"state": "@class"
}
},
{
"id": "info",
"title": "Request info",
"role": "table",
"from": "table",
"list": "css:table#fields"
},
{
"id": "comments",
"title": "Comments",
"role": "text",
"value": "css:#comments .cm div@text"
}
]
}
},
"display": {"defaults": 1, "blocks": {"flow": {"show": "horizontal"}}}
}12.6 dashboard: approval center (actions and embeds)#
A fictional site. Approve, reject and comment right in the dashboard, plus a self-drawn stats card and a piece of the site's approval progress. The three item actions show three styles: approve = steps (accept the page's confirm box, then click the original button), reject = a dialog plus a typed reason, comment = a direct request (with CSRF). Every action has success and error. The app asks for confirmation before running; the rule contains write actions, so it needs one-time authorization.
{
"id": "com.example.ops.approvals",
"name": "Example Approval Center",
"version": 1,
"contentType": "dashboard",
"domains": ["ops.example.com"],
"requiresWebView": true,
"requires": ["board.blocks", "board.actions", "board.embed", "display.blocks"],
"pages": {
"board": {
"request": {
"url": "https://ops.example.com/oa.html",
"render": {"waitFor": "#pending a.card", "timeoutMs": 15000}
},
"title": "css:h1@text",
"blocks": [
{
"id": "todo",
"title": "Awaiting my approval",
"role": "items",
"list": "css:#pending .apw",
"fields": {
"title": "css:a.card .t@ownText",
"url": "css:a.card@href",
"key": "@data-id",
"summary": "tpl:{{css:.meta span:nth-child(1)@text}} · {{css:.meta span:nth-child(2)@text}} · {{css:.meta span:nth-child(3)@text}}",
"latestText": "css:.amt@text"
},
"itemActions": [
{
"id": "approve",
"title": "Approve",
"style": "primary",
"icon": "checkmark.circle",
"run": {
"scope": "row",
"steps": [{"acceptDialog": true}, {"click": "button.btn-approve"}]
},
"success": {"text": ".toast.success"},
"error": "#alert .alert.error"
},
{
"id": "reject",
"title": "Reject",
"style": "destructive",
"icon": "xmark.circle",
"inputs": [
{
"id": "reason",
"label": "Reason for rejection",
"kind": "multiline",
"required": true,
"placeholder": "Please enter a reason"
}
],
"run": {
"scope": "row",
"steps": [
{"click": "button.btn-reject"},
{"waitFor": "#reject-modal.open", "timeout": 3000},
{
"fill": "#reject-reason",
"from": "reason",
"scope": "page"
},
{"click": "#reject-confirm", "scope": "page"}
]
},
"success": {"text": ".toast.success"},
"error": "#reject-error"
},
{
"id": "comment",
"title": "Comment",
"icon": "text.bubble",
"inputs": [
{
"id": "text",
"label": "Comment",
"kind": "multiline",
"required": true
}
],
"run": {
"request": {
"method": "POST",
"url": "/api/approvals/{{item.key}}/comment",
"body": {"text": "{{inputs.text}}"},
"csrf": "meta[name=csrf-token]"
}
},
"success": {"json": "$.ok == true"}
}
]
},
{
"id": "budgets",
"title": "Department budgets",
"role": "progress",
"list": "css:#budgets .brow",
"fields": {
"label": "css:.h span:nth-child(1)@text",
"value": "css:progress@value || css:.bar i@style | re:/width:(\\d+)/#1",
"text": "css:.h span:nth-child(2)@text"
}
},
{
"id": "stats",
"title": "Approval stats",
"role": "embed",
"embed": "html",
"height": 220,
"scripts": true,
"html": "<div class=\"s\"><b id=\"n\">0</b> <span> pending</span><div id=\"top\"></div></div><style>.s{font-family:var(--ui-font);color:var(--ui-text)}.s b{font:600 40px var(--ui-font-serif);color:var(--ui-accent)}.s span{color:var(--ui-text2)}#top{margin-top:8px;font-size:13px;color:var(--ui-text2)}</style><script>var t=[].concat(unweb.data.types||[]);document.getElementById(\"n\").textContent=t.length;document.getElementById(\"top\").textContent=t.slice(0,3).join(\" / \")</script>",
"data": {"types": "css:#pending .apw .meta span:nth-child(2)@text"}
},
{
"id": "flow",
"title": "Latest approval progress",
"role": "embed",
"embed": "fragment",
"url": "/approval.html?id=AP-1040",
"selector": "ol.steps",
"height": 260
}
]
}
},
"display": {"defaults": 1, "blocks": {"budgets": {"span": "half"}}}
}12.7 dashboard: expense form#
role: "form" reads the page form's inputs automatically; after submitting, success is judged by the page's redirect and the result page opens.
{
"id": "com.example.ops.expense",
"name": "Example Expense Request",
"version": 1,
"contentType": "dashboard",
"domains": ["ops.example.com"],
"requiresWebView": true,
"requires": ["board.blocks", "board.forms"],
"urlPatterns": ["https://ops.example.com/expense.html*"],
"pages": {
"board": {
"request": {
"url": "https://ops.example.com/expense.html",
"render": {"waitFor": "form#expense", "timeoutMs": 15000}
},
"title": "css:h1@text",
"blocks": [
{
"id": "expense",
"title": "Expense request",
"role": "form",
"from": "form",
"list": "css:form#expense",
"submit": {
"id": "submit",
"title": "Submit request",
"success": {"url": "approval\\.html\\?id="},
"error": "#form-error",
"after": "open"
}
}
]
}
}
}