Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inlined Webpack JS file doesn't work

I have a webpack project (based on https://github.com/vuejs/vue-webpack-example) which generates an index.html file and a javascript file containing the application.

Everything works fine when I include the JavaScript like this:

<script src="static/js/app.js"></script>

When I try to include the contents of static/js/app.js directly in a script tag (because we need to end up with a single .html file) it doesn't work anymore. It looks like the javascript doesn't get exectuted at all:

<script>!function(e){function t(i){if(n[i])return...</script>

I extracted the application into 3 files (manifest.js, vendor.js and app.js) where vendor.js contains the libraries I need from node_modules. It works as long as I don't include vendor.js directly. So I can inline the manifest.js and app.js but not vendor.js.

Any ideas why the inlined js doesn't work but the included js via an url does work? Until now I thought js would behave exactly the same, no matter how it's included.

like image 371
Moritur Avatar asked Mar 25 '26 19:03

Moritur


1 Answers

I figured out what's wrong.

Some browsers (I tested Safari and Chrome on Mac) seem to not like <script> tags which have an opening script tag somewhere inside them. Even though all the closing script tags are escaped (like document.write("</script"+">"))

Strangely this does work in simple example like this one:

<script>
    document.write("<script>alert(1)</script"+">")
</script>

In complex examples (like this one: https://gist.github.com/Sopamo/f2a591b4afaa91238516b82006e85845) it only works when all <script> tags are "escaped". Maybe someone can find out what's the difference between the simple and the complex example.

In my case I used the inline example of the html-webpack-plugin which I modified as follows:

script(type="text/javascript") !{compilation.assets[jsFile.substr(htmlWebpackPlugin.files.publicPath.length)].source().replace(/<script>/g,'<script"+">')}

Note the replace() call at the end.

like image 58
Moritur Avatar answered Mar 27 '26 07:03

Moritur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!