From aead4100eaaf6a6be032209504b7158e18c67c51 Mon Sep 17 00:00:00 2001
From: Nikhil Tanwar <2002nikhiltanwar@gmail.com>
Date: Fri, 29 Jul 2022 01:04:33 +0530
Subject: [PATCH] Add custom CSS and JS support
Added an event listener for message event.
The idea is the website which embeds the widget will send a message using postMessage().
The expected message is:
{
css: // custom CSS code
js: // custom JS code
}
---
static/skin/widget.js | 20 ++++++++++++++++++++
test/server.cpp | 2 +-
2 files changed, 21 insertions(+), 1 deletion(-)
diff --git a/static/skin/widget.js b/static/skin/widget.js
index 3d0067508..3250ab7de 100644
--- a/static/skin/widget.js
+++ b/static/skin/widget.js
@@ -51,6 +51,25 @@ function insertNewCssRules(stylesheet, ruleList) {
}
}
+function addCustomCss(cssCode) {
+ let customCSS = document.createElement('style');
+ customCSS.innerHTML = cssCode;
+ document.head.appendChild(customCSS);
+}
+
+function addCustomJs(jsCode) {
+ new Function(`"use strict";${jsCode}`)();
+}
+
+function handleMessages(event) {
+ if ('css' in event.data) {
+ addCustomCss(event.data.css);
+ }
+ if ('js' in event.data) {
+ addCustomJs(event.data.js);
+ }
+}
+
function handleWidget() {
const params = new URLSearchParams(window.location.search || filters || '');
const widgetStyleElem = document.createElement('style');
@@ -82,4 +101,5 @@ function handleWidget() {
kiwixServe.updateBookCount();
}
+window.addEventListener('message', handleMessages);
handleWidget();
\ No newline at end of file
diff --git a/test/server.cpp b/test/server.cpp
index 886fcf542..cf186cd87 100644
--- a/test/server.cpp
+++ b/test/server.cpp
@@ -184,7 +184,7 @@ R"EXPECTEDRESULT( href="/ROOT/skin/index.css?cacheid=56e818cd"
src: url("/ROOT/skin/fonts/Roboto.ttf?cacheid=84d10248") format("truetype");
-
+
)EXPECTEDRESULT"
},
{