Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: make injected styles compatible with strict CSP
pederbe3899cb556cb5
diff --git a/bin/utils/combine.ts b/bin/utils/combine.tsindex e2924f2e..5b2a6f0b 100644--- a/bin/utils/combine.ts+++ b/bin/utils/combine.ts@@ -7,9 +7,13 @@ export default async function combineFiles(files: string[], output: string) {const fileContent = await fs.readFile(file, 'utf-8');return `window.addEventListener('DOMContentLoaded', (_event) => {const css = ${JSON.stringify(fileContent)};- const style = document.createElement('style');- style.textContent = css;- document.head.appendChild(style);+ if (typeof window.__PAKE_INJECT_STYLE__ === 'function') {+ window.__PAKE_INJECT_STYLE__(css);+ } else {+ const style = document.createElement('style');+ style.textContent = css;+ document.head.appendChild(style);+ }});`;}diff --git a/dist/cli.js b/dist/cli.jsindex 2e895e66..cde62ac3 100644--- a/dist/cli.js+++ b/dist/cli.js@@ -488,9 +488,13 @@ async function combineFiles(files, output) {const fileContent = await fs$1.readFile(file, 'utf-8');return `window.addEventListener('DOMContentLoaded', (_event) => {const css = ${JSON.stringify(fileContent)};- const style = document.createElement('style');- style.textContent = css;- document.head.appendChild(style);+ if (typeof window.__PAKE_INJECT_STYLE__ === 'function') {+ window.__PAKE_INJECT_STYLE__(css);+ } else {+ const style = document.createElement('style');+ style.textContent = css;+ document.head.appendChild(style);+ }});`;}const fileContent = await fs$1.readFile(file);diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 2a55c2bc..1f371d60 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -503,6 +503,8 @@ fn build_window(// so only inject its ~700 lines when the feature is on. Avoids parsing the// find UI on every page load in the common (find-off) case. Matches the// enable_find gating already applied to the Find menu item.+ window_builder = window_builder.initialization_script(include_str!("../inject/styles.js"));+if window_config.enable_find {window_builder = window_builder.initialization_script(include_str!("../inject/find.js"));}diff --git a/src-tauri/src/inject/find.js b/src-tauri/src/inject/find.jsindex 6c09dd34..ed333ca6 100644--- a/src-tauri/src/inject/find.js+++ b/src-tauri/src/inject/find.js@@ -199,9 +199,7 @@return;}- const style = document.createElement("style");- style.id = STYLE_ID;- style.textContent = `+ const css = `#${PANEL_ID} {position: fixed;top: 14px;@@ -312,9 +310,16 @@}`;- (document.head || document.body || document.documentElement)?.appendChild(- style,- );+ if (typeof window.__PAKE_INJECT_STYLE__ === "function") {+ window.__PAKE_INJECT_STYLE__(css, STYLE_ID);+ } else {+ const style = document.createElement("style");+ style.id = STYLE_ID;+ style.textContent = css;+ (document.head || document.body || document.documentElement)?.appendChild(+ style,+ );+ }}function createButton(label, title, onClick) {diff --git a/src-tauri/src/inject/fullscreen.js b/src-tauri/src/inject/fullscreen.jsindex c9f2485a..3e3ae996 100644--- a/src-tauri/src/inject/fullscreen.js+++ b/src-tauri/src/inject/fullscreen.js@@ -25,9 +25,7 @@let monitorId = null;if (!document.getElementById("pake-fullscreen-style")) {- const styleEl = document.createElement("style");- styleEl.id = "pake-fullscreen-style";- styleEl.textContent = `+ const css = `body.pake-fullscreen-active {overflow: hidden !important;}@@ -51,7 +49,14 @@object-fit: contain !important;}`;- document.head.appendChild(styleEl);+ if (typeof window.__PAKE_INJECT_STYLE__ === "function") {+ window.__PAKE_INJECT_STYLE__(css, "pake-fullscreen-style");+ } else {+ const styleEl = document.createElement("style");+ styleEl.id = "pake-fullscreen-style";+ styleEl.textContent = css;+ document.head.appendChild(styleEl);+ }}function startFullscreenMonitor() {diff --git a/src-tauri/src/inject/style.js b/src-tauri/src/inject/style.jsindex 7950beb3..54a571a5 100644--- a/src-tauri/src/inject/style.js+++ b/src-tauri/src/inject/style.js@@ -320,9 +320,14 @@ window.addEventListener("DOMContentLoaded", (_event) => {padding-top: 36px;}`;- const contentStyleElement = document.createElement("style");- contentStyleElement.textContent = contentCSS;- document.head.appendChild(contentStyleElement);+ if (typeof window.__PAKE_INJECT_STYLE__ === "function") {+ window.__PAKE_INJECT_STYLE__(contentCSS, "pake-content-style");+ } else {+ const contentStyleElement = document.createElement("style");+ contentStyleElement.id = "pake-content-style";+ contentStyleElement.textContent = contentCSS;+ document.head.appendChild(contentStyleElement);+ }// Top spacing adapts to head-hiding scenariosconst topPaddingCSS = `@@ -499,8 +504,7 @@ window.addEventListener("DOMContentLoaded", (_event) => {`;const isMac = /Mac/i.test(navigator.userAgent);if (hasImmersiveHeader(window["pakeConfig"])) {- const topPaddingStyleElement = document.createElement("style");- topPaddingStyleElement.textContent = isMac+ const topPaddingCSSForPlatform = isMac? topPaddingCSS: `#pake-top-dom:active {@@ -521,6 +525,16 @@ window.addEventListener("DOMContentLoaded", (_event) => {z-index: 99999;}`;- document.head.appendChild(topPaddingStyleElement);+ if (typeof window.__PAKE_INJECT_STYLE__ === "function") {+ window.__PAKE_INJECT_STYLE__(+ topPaddingCSSForPlatform,+ "pake-top-padding-style",+ );+ } else {+ const topPaddingStyleElement = document.createElement("style");+ topPaddingStyleElement.id = "pake-top-padding-style";+ topPaddingStyleElement.textContent = topPaddingCSSForPlatform;+ document.head.appendChild(topPaddingStyleElement);+ }}});diff --git a/src-tauri/src/inject/styles.js b/src-tauri/src/inject/styles.jsnew file mode 100644index 00000000..477ea6d8--- /dev/null+++ b/src-tauri/src/inject/styles.js@@ -0,0 +1,72 @@+(function () {+ const INJECT_STYLE_KEY = "__PAKE_INJECT_STYLE__";+ const adoptedSheetsById = new Map();++ if (typeof window[INJECT_STYLE_KEY] === "function") {+ return;+ }++ function injectWithAdoptedStyleSheet(css, id) {+ try {+ if (+ typeof window.CSSStyleSheet !== "function" ||+ !("adoptedStyleSheets" in document) ||+ /^\s*@import\b/m.test(css)+ ) {+ return null;+ }++ const currentSheets = document.adoptedStyleSheets;+ const sheet = new window.CSSStyleSheet();+ sheet.replaceSync(css);+ document.adoptedStyleSheets = Array.from(currentSheets).concat(sheet);++ if (!Array.from(document.adoptedStyleSheets).includes(sheet)) {+ return null;+ }++ if (id) {+ adoptedSheetsById.set(id, sheet);+ }+ return sheet;+ } catch (_error) {+ return null;+ }+ }++ window[INJECT_STYLE_KEY] = function (css, id) {+ if (id) {+ const existingElement = document.getElementById(id);+ if (existingElement) {+ return existingElement;+ }++ const existingSheet = adoptedSheetsById.get(id);+ if (existingSheet) {+ try {+ if (Array.from(document.adoptedStyleSheets).includes(existingSheet)) {+ return existingSheet;+ }+ } catch (_error) {+ // Recreate the sheet when the document's adopted-sheet list is unavailable.+ }+ adoptedSheetsById.delete(id);+ }+ }++ const sheet = injectWithAdoptedStyleSheet(css, id);+ if (sheet) {+ return sheet;+ }++ const style = document.createElement("style");+ if (id) {+ style.id = id;+ }+ style.textContent = css;+ (document.head || document.body || document.documentElement)?.appendChild(+ style,+ );+ return style;+ };+})();diff --git a/tests/unit/combine.test.ts b/tests/unit/combine.test.tsindex dea21473..6df37de0 100644--- a/tests/unit/combine.test.ts+++ b/tests/unit/combine.test.ts@@ -42,8 +42,24 @@ describe('combineFiles', () => {const result = await fs.readFile(out, 'utf-8');expect(() => new Function(result)).not.toThrow();- expect(result).toContain('document.head.appendChild');+ expect(result).toContain('window.__PAKE_INJECT_STYLE__');expect(result).toContain(JSON.stringify('body { color: red; }'));++ const handlers: Array<() => void> = [];+ const injectedCss: string[] = [];+ const runtimeWindow = {+ addEventListener(_event: string, handler: () => void) {+ handlers.push(handler);+ },+ __PAKE_INJECT_STYLE__(css: string) {+ injectedCss.push(css);+ },+ };++ new Function('window', 'document', result)(runtimeWindow, {});+ handlers[0]();++ expect(injectedCss).toEqual(['body { color: red; }']);});it('returns the input file list', async () => {diff --git a/tests/unit/find-shortcuts.test.js b/tests/unit/find-shortcuts.test.jsindex c6de79c3..4231da8d 100644--- a/tests/unit/find-shortcuts.test.js+++ b/tests/unit/find-shortcuts.test.js@@ -135,6 +135,7 @@ function createDocument(textNodes) {querySelectorAll() {return [];},+ adoptedStyleSheets: [],};return document;@@ -169,6 +170,10 @@ function loadFindScript({path.join(process.cwd(), "src-tauri/src/inject/find.js"),"utf-8",);+ const styleSource = fs.readFileSync(+ path.join(process.cwd(), "src-tauri/src/inject/styles.js"),+ "utf-8",+ );const context = {console,setTimeout,@@ -182,12 +187,18 @@ function loadFindScript({},window: {pakeConfig: { enable_find: enabled },+ CSSStyleSheet: class CSSStyleSheet {+ replaceSync(css) {+ this.cssText = css;+ }+ },},document: createDocument(nodes),};context.window.NodeFilter = context.NodeFilter;context.window.navigator = context.navigator;+ runInNewContext(styleSource, context);runInNewContext(source, context);return context;}@@ -240,6 +251,14 @@ describe("Find injection", () => {expect(previousEvent.propagationStopped).toBe(true);});+ it("uses the shared style injector for the find panel", () => {+ const context = loadFindScript({ enabled: true });++ expect(context.window.pakeFind.open().isOpen).toBe(true);+ expect(context.document.adoptedStyleSheets).toHaveLength(1);+ expect(context.document.head.children).toHaveLength(0);+ });+it("leaves macOS Find shortcuts to the native menu", () => {const context = loadFindScript({enabled: true,diff --git a/tests/unit/style-injection.test.js b/tests/unit/style-injection.test.jsnew file mode 100644index 00000000..4c068de5--- /dev/null+++ b/tests/unit/style-injection.test.js@@ -0,0 +1,109 @@+import fs from "fs";+import path from "path";+import { runInNewContext } from "node:vm";+import { describe, expect, it } from "vitest";++const source = fs.readFileSync(+ path.join(process.cwd(), "src-tauri/src/inject/styles.js"),+ "utf-8",+);++function loadStyleHelper({ supportsAdoptedStyleSheets }) {+ const appendedStyles = [];+ const document = {+ head: {+ appendChild(style) {+ appendedStyles.push(style);+ return style;+ },+ },+ createElement(tagName) {+ return { tagName, id: "", textContent: "" };+ },+ getElementById() {+ return null;+ },+ };++ if (supportsAdoptedStyleSheets) {+ document.adoptedStyleSheets = [];+ }++ const context = {+ document,+ window: {+ CSSStyleSheet: class CSSStyleSheet {+ replaceSync(css) {+ this.cssText = css;+ }+ },+ },+ };++ runInNewContext(source, context);+ return { appendedStyles, context };+}++describe("Pake style injection", () => {+ it("uses adopted style sheets when the page blocks style elements", () => {+ const { appendedStyles, context } = loadStyleHelper({+ supportsAdoptedStyleSheets: true,+ });+ const injectStyle = context.window.__PAKE_INJECT_STYLE__;++ const sheet = injectStyle("body { color: red; }", "pake-test-style");++ expect(sheet.cssText).toBe("body { color: red; }");+ expect(context.document.adoptedStyleSheets).toEqual([sheet]);+ expect(appendedStyles).toHaveLength(0);+ expect(injectStyle("body { color: blue; }", "pake-test-style")).toBe(sheet);+ });++ it("recreates a cached sheet after the page removes it", () => {+ const { context } = loadStyleHelper({+ supportsAdoptedStyleSheets: true,+ });+ const injectStyle = context.window.__PAKE_INJECT_STYLE__;++ const firstSheet = injectStyle("body { color: red; }", "pake-test-style");+ context.document.adoptedStyleSheets = [];+ const secondSheet = injectStyle("body { color: blue; }", "pake-test-style");++ expect(secondSheet).not.toBe(firstSheet);+ expect(secondSheet.cssText).toBe("body { color: blue; }");+ expect(context.document.adoptedStyleSheets).toEqual([secondSheet]);+ });++ it("keeps CSS imports on the style-element path", () => {+ const { appendedStyles, context } = loadStyleHelper({+ supportsAdoptedStyleSheets: true,+ });++ context.window.__PAKE_INJECT_STYLE__(+ '@import url("theme.css");\nbody { color: red; }',+ "pake-test-style",+ );++ expect(context.document.adoptedStyleSheets).toHaveLength(0);+ expect(appendedStyles).toHaveLength(1);+ expect(appendedStyles[0].textContent).toContain("@import");+ });++ it("falls back to a style element when adopted style sheets are unavailable", () => {+ const { appendedStyles, context } = loadStyleHelper({+ supportsAdoptedStyleSheets: false,+ });++ context.window.__PAKE_INJECT_STYLE__(+ "body { color: red; }",+ "pake-test-style",+ );++ expect(appendedStyles).toHaveLength(1);+ expect(appendedStyles[0]).toMatchObject({+ tagName: "style",+ id: "pake-test-style",+ textContent: "body { color: red; }",+ });+ });+});