Skip to content
Open
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
38 changes: 32 additions & 6 deletions htmlpreview.js
Original file line number Diff line number Diff line change
Expand Up @@ -381,16 +381,42 @@
const loadHTML = function (data) {
if (data) {
// Add <base> just after <head>
// and replace <script type="text/javascript">
// with <script type="text/htmlpreview">
data = data.replace(
/<head([^>]*)>/i,
'<head$1><base href="' + rawFileUrl + '">'
).replace(
// eslint-disable-next-line @stylistic/js/max-len
/<script(\s*src=["'][^"']*["'])?(\s*type=["'](text|application)\/javascript["'])?/gi,
'<script type="text/htmlpreview"$1'
);

// Only rewrite <script> tags that are local or from a git forge
data = data.replace(/<script(\s+[^>]*)?>/gi, function (match) {
// Extract src attribute if present
const srcMatch = match.match(/src=["']([^"']+)["']/i);
if (srcMatch) {
let src = srcMatch[1];
let absSrc;
try {
absSrc = new URL(src, rawFileUrl).href;
} catch (e) {
absSrc = src; // fallback, treat as is
}
// Only rewrite if src is a git forge file
if (isGitForgeFileUrl(absSrc)) {
// Remove any existing type attribute
let tag = match.replace(/type=["'][^"']*["']/i, '');
// Add our type
tag = tag.replace('<script', '<script type="text/htmlpreview"');
return tag;
} else {
// Leave external scripts (like CDN or local) untouched
return match;
}
} else {
// Inline scripts: rewrite
let tag = match.replace(/type=["'][^"']*["']/i, '');
tag = tag.replace('<script', '<script type="text/htmlpreview"');
return tag;
}
});

// Delay updating document to have it cleared before
setTimeout(function () {
document.open();
Expand Down