Search code examples
javascriptvue.jsvuejs2code-injection

vue js - HTML injection from plain text into a vue component


I'm working on migrating some code from ASPX to VUE.JS

In the previous system exists the functionality that gets the plain text and injected into the HTML (Like messages with text, images, links, and inputs). In VUE the injected HTML doesn't work fine...

I created a demo with the root problem.

CodeSandbox Exercise

Where basically we want to inject HTML into a VUE component like HTML... and works. But inside the plain HTML also it's included JS code.

This is a flow of the problem: flow

Some suggestions on how to work around this problem? The plain text could have different JS functions (could be more than 50 different scenarios)


Solution

  • Javascript is not being executed with injected code like that. You can test that by writing console.log('test') into the <script> tag.

    To solve this problem you can include this little regex function after your replace function, which evaluates every script tag.

    codeBlock.match(/(?<=<script>).*?(?=<\/script>)/gms).forEach(function (match) {
      window.eval(match);
    });
    

    Here is also a forked version of your demo with the fix: https://codesandbox.io/s/vue-injection-problem-forked-wigzr?file=/src/components/HelloWorld.vue