How to insert script with inner HTML?

2,346 views
Skip to first unread message

Rory

unread,
May 17, 2021, 9:18:17 PM5/17/21
to Chromium Extensions
I am currently developing a chrome extension with a designer, and they (the designer) have put together some great assets using a service called Webflow. Webflow allows users to design webpages in a low-code interface that can later be exported to html, js and css. 

The resulting html file has a combination of inline and external scripts in a variety of different places. For the sake of example, let's assume the html of the asset looks a little like this:

```html
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<link href="link/to/a/css/file" rel="stylesheet" type="text/css">
<script src="link/to/an/external/script.js" type="text/javascript"></script>
<script type="text/javascript">
console.log('this is an inline script')
</script>
</head>
<body class="body">
<div id="extension-contents">
...
</div>
<script src="another/js/file.js" type="text/javascript" integrity="this-is-a-sha256-hash" crossorigin="anonymous"></script></body>
</html>
```

Ideally, our chrome extension will insert this html into the webpage at a given point (when they visit a particular website, for example). We do this by appending an element to the DOM of the webpage and setting the "innerHTML" property of that element to the source of our html file. However, none of the javascript that is referenced within the html is being evaluated. 

I've done some research and now understand that inserted inline javascript will not be evaluated when part of an element's innerHTML attribute, but what I don't understand is a good, alternative way of keeping the javascript functionality of our assets. I've tried executing the relevant scripts as content scripts or inserting them with chrome.scripting but because content-scripts run in an isolated environment the javascript does not modifying the relevant assets in the inserted html file.

Has anyone encountered an issue like this before? 
Message has been deleted

wOxxOm

unread,
May 18, 2021, 10:11:50 AM5/18/21
to Chromium Extensions, Rory
Assigning to innerHTML doesn't run scripts intentionally per the HTML specification. The workaround is to recreate the elements explicitly, see https://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml

A better approach might be to put this HTML inside a an html file, expose it via web_accessible_resources, and load it in an iframe. The iframe scripts will run automatically and will have access to chrome API just like the extension popup or options page. See https://stackoverflow.com/a/25100953

Reply all
Reply to author
Forward
0 new messages