Utility Function to Convert Relative URLs to Absolute URLs
You can create a utility function that takes the HTML string and a base URL, and then replaces all relative URLs with absolute URLs.
function convertRelativeToAbsolute(html, baseUrl) {
// Create a DOM parser to parse the HTML string
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Get all the image elements
const images = doc.querySelectorAll('img');
// Replace the src attribute for each image
images.forEach(img => {
const src = img.getAttribute('src');
// If the src is relative, convert it to absolute
if (src && !src.startsWith('http')) {
img.setAttribute('src', new URL(src, baseUrl).toString());
}
});
// Serialize the document back to a string
return doc.documentElement.outerHTML;
}
Once you have the utility function, you can use it within your React component to render the HTML with the updated image URLs.
convertRelativeToAbsolute(html, baseUrl): This function parses the HTML string, finds all tags, and converts any relative src attributes to absolute URLs using the provided baseUrl.
dangerouslySetInnerHTML: This is a React prop used to set HTML content. It’s called "dangerous" because it can expose your app to cross-site scripting (XSS) attacks if you’re not careful with the content you pass to it. Ensure that the HTML content you’re rendering is sanitized if it comes from an untrusted source.
With this approach, you’ll be able to convert relative image URLs to absolute URLs in your React application.
Solved -- RichTextEditor Absolute Url: How?
I tried this custom config into appsetting to setup TinyMCE with absolute url because I need the content from a remote NextJS, but don't work.
I read the TinyMCE help: https://www.tiny.cloud/docs/tinymce/latest/url-handling/
How Do you solve this problem?
I solved with code...
Once you have the utility function, you can use it within your React component to render the HTML with the updated image URLs.
You can now use this component in your React application by passing the HTML string and the base URL:
Explanation
convertRelativeToAbsolute(html, baseUrl): This function parses the HTML string, finds all tags, and converts any relative src attributes to absolute URLs using the provided baseUrl. dangerouslySetInnerHTML: This is a React prop used to set HTML content. It’s called "dangerous" because it can expose your app to cross-site scripting (XSS) attacks if you’re not careful with the content you pass to it. Ensure that the HTML content you’re rendering is sanitized if it comes from an untrusted source. With this approach, you’ll be able to convert relative image URLs to absolute URLs in your React application.
is working on a reply...