Would using createElement instead of template literals prevent XSS?

48 Views Asked by At

My messenger application is rendering each dialog using a template literal. This is causing unwanted behavior such as the last_message displaying links, images, or even executing scripts instead of just showing plain text. My messenger should only supports text messaging so users are unable to send images, voice attachments, etc.

Example incoming message:

var app = document.querySelector('body'); app.innerHTML = '<img src="x" onerror="alert(1)">';

  renderDialogs: () => {
    const dialogList = document.getElementById('dialogsList');
    dialogList.textContent = '';

    const df = document.createDocumentFragment();

    dialogs.list.forEach(
      ({
        id,
        created,
        modified,
        username,
        other_user_id,
        unread_count,
        last_message,
      }) => {
        const btn = document.createElement('button');
        btn.classList =
          'list-group-item list-group-item-action list-group-item';
        btn.dataset.username = username;
        btn.dataset.userId = other_user_id;

        const btnContent = `
        <div class="d-flex flex-column gap-1 disable-pointer-events">
          <h5 class="mb-0 fs-6">${username}</h5>
          <p class="mb-0 text-muted preview-text">${last_message.text}</p>
          <p class="mb-0 dialog-unread"><span class="dialog-unread-count">${unread_count}</span> unread messages</p>
        </div>
      `;

        btn.insertAdjacentHTML('beforeend', btnContent);
        df.appendChild(btn);
      },
    );
    dialogList.appendChild(df);
  },

Would converting the following to use createElement prevent this mess? I used to use python bleach package to sanitize text in the backend, but it's now deprecated.

0

There are 0 best solutions below