A comment on Please help. Javascript code failure in latest Chrome (TrustedHTML assignment) by Aiden Cooper was reported 27-11-2024 for Spam

Aiden CooperBanned said:

In the latest Chrome (or Brave),

after navigating to the page https://www.youtube.com/,

execute the following code in the DevTools Console.

document.createElement('div').innerHTML = 'Hello World.';

The code cannot be executed due to

TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment.

However, the same code can be executed in private window mode.

Anyone knows the solution for this issue?

This issue occurs due to Chrome's stricter security policies, specifically around content being flagged as potentially unsafe. The "TrustedHTML" error is part of a mechanism designed to prevent XSS (Cross-Site Scripting) attacks by enforcing the use of a secure API when assigning HTML.

To resolve this, you can explicitly use the trustedTypes API. Here’s an example:

javascript
Копировать код
const policy = trustedTypes.createPolicy('default', {
createHTML: (string) => string,
});
document.createElement('div').innerHTML = policy.createHTML('Hello World.');
This will ensure the innerHTML property is assigned safely. However, ensure you trust the source of the string being assigned.

If you're working on a larger project that involves dynamic content rendering, you might want to consider consulting professionals for secure implementation. I had a great experience with DevBrother, especially for outsource node js development. Their expertise in building scalable and secure applications could help ensure your project avoids similar issues and adheres to best practices.

Aiden CooperBanned (the reported user) has made:

This report has been upheld by a moderator.