I've created an email editor to allow my users created their custom email messages. The page that contains the editor has also a preview of the custom email, in PHP <div id="email_preview"><?= $email_preview ?></div>
.
The problem is that if the user types in some CSS, than the elements of the containing page can be modified.
Is there a way to make the preview not influence the containing page?
The most common way for doing this is by using an iFrame, or setup a styling convention/script. By using an iFrame you can keep their content/styling separate from its container.
Rewriting all of the styles of the inbound HTML is the other alternative. (prefixing the styles or similar).
Your code <?= $email_preview ?>
is outputting markup to the page when it loads. So all of the CSS they've entered is present in the page and your browser will render it accordingly.
The only way you could do this is if you stop the user inputting anything unless it applies to certain named ID's/classes.
For example if they enter
p {
font-size: 14px;
}
Before saving this - and outputting it with <?= $email_preview ?>
you could change it to:
#email_preview p {
font-size: 14px;
}
This means their CSS is only applied within #email_preview
as opposed to all p
elements on the rest of the page.
The other option would be to load the content in a modal window which excludes anything other than the markup stored in $email_preview
. This is basically a blank web page with no other markup so it can only affect the intended content. This is like isolating the content within a page but is useful for preview purposes like this (amongst other things).