correctly preservig formatting. see #70

This commit is contained in:
mic 2024-06-26 22:22:57 +02:00
parent d71301f9e1
commit 7f0a50be42

View file

@ -350,34 +350,37 @@ async function doProceed(message, customText = ''){
operation_done(); operation_done();
} }
function removeTagsAndReturnHTML(rootElement, removeTags, preserveTags) { function removeTagsAndReturnHTML(rootElement, removeTags, preserveTags) {
removeTags.forEach(tag => {
const elements = rootElement.getElementsByTagName(tag);
while (elements.length > 0) {
const element = elements[0];
const fragment = document.createDocumentFragment(); const fragment = document.createDocumentFragment();
// Preserve specified tags and their children in the correct order function handleElement(element) {
let child = element.firstChild; let child = element.firstChild;
while (child) { while (child) {
console.log(">>>>>>>>>>>> ciclo child: " + child.tagName.toLowerCase());
const nextSibling = child.nextSibling; const nextSibling = child.nextSibling;
if (preserveTags.includes(child.tagName.toLowerCase())) { if (preserveTags.includes(child.nodeName.toLowerCase())) {
console.log(">>>>>>>>>>>> preserve: " + child.tagName.toLowerCase()); //console.log(">>>>>>>>>>>> preserve child: " + child.tagName.toLowerCase());
fragment.appendChild(child); fragment.appendChild(child);
} else if (child.nodeType === Node.ELEMENT_NODE) {
//console.log(">>>>>>>>>>>> handleElement(child): " + child.tagName.toLowerCase());
handleElement(child);
} }
child = nextSibling; child = nextSibling;
} }
// Append preserved elements back to the parent of the removed element
element.parentNode.insertBefore(fragment, element);
// Remove the element and all its remaining children
element.parentNode.removeChild(element);
} }
removeTags.forEach(tag => {
const elements = Array.from(rootElement.getElementsByTagName(tag));
elements.forEach(element => {
handleElement(element);
element.parentNode.insertBefore(fragment.cloneNode(true), element);
element.parentNode.removeChild(element);
//console.log(">>>>>>>>>>>> removeChild: " + element.tagName.toLowerCase());
});
}); });
replaceNewlinesWithBr(rootElement); replaceNewlinesWithBr(rootElement);
//console.log(">>>>>>>>>>>> rootElement.innerHTML: " + rootElement.innerHTML);
// Return the updated HTML as a string // Return the updated HTML as a string
return rootElement.innerHTML; return rootElement.innerHTML;
} }
@ -403,6 +406,7 @@ function removeTagsAndReturnHTML(rootElement, removeTags, preserveTags) {
} }
} }
// In the content script // In the content script
browser.runtime.onMessage.addListener((message, sender, sendResponse) => { browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.command === "chatgpt_send") { if (message.command === "chatgpt_send") {