Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sanitize css before sending to Anki #1722

Merged
merged 3 commits into from
Dec 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading