Skip to content

Commit

Permalink
Sanitize css before sending to Anki (#1722)
Browse files Browse the repository at this point in the history
* Sanitize css before sending to anki

* Catch sanitizer fails only when `new CSSStyleSheet()` is not available

* Lint
  • Loading branch information
Kuuuube authored Dec 30, 2024
1 parent f0849e9 commit 8f4cf51
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
21 changes: 21 additions & 0 deletions ext/js/core/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import {log} from './log.js';


/**
* Converts any string into a form that can be passed into the RegExp constructor.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Expand Down Expand Up @@ -262,3 +265,21 @@ export function deferPromise() {
export function promiseTimeout(delay) {
return delay <= 0 ? Promise.resolve() : new Promise((resolve) => { setTimeout(resolve, delay); });
}

/**
* @param {string} css
* @returns {string}
*/
export function sanitizeCSS(css) {
let sanitizer;
// As of 2023/03/xx, all latest browser versions support this but some forks may lag behind
try {
sanitizer = new CSSStyleSheet();
} catch (e) {
log.log('Failed to sanitize dictionary styles');
log.warn(e);
return css;
}
sanitizer.replaceSync(css);
return [...sanitizer.cssRules].map((rule) => rule.cssText || '').join('\n');
}
4 changes: 2 additions & 2 deletions ext/js/data/anki-note-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
*/

import {ExtensionError} from '../core/extension-error.js';
import {deferPromise} from '../core/utilities.js';
import {deferPromise, sanitizeCSS} from '../core/utilities.js';
import {convertHiraganaToKatakana, convertKatakanaToHiragana} from '../language/ja/japanese.js';
import {cloneFieldMarkerPattern, getRootDeckName} from './anki-util.js';

Expand Down Expand Up @@ -192,7 +192,7 @@ export class AnkiNoteBuilder {
for (const dictionary of dictionaries) {
const {name, styles} = dictionary;
if (typeof styles === 'string') {
styleMap.set(name, styles);
styleMap.set(name, sanitizeCSS(styles));
}
}
return styleMap;
Expand Down

0 comments on commit 8f4cf51

Please sign in to comment.