1

I'm developing an extension for Microsoft Edge and have learned from the docs here https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/creating-an-extension#writing-a-more-complex-extension that I can use Javascript for data manipulation.

For some reason though, when I try to modify a DOM element like this:

<!DOCTYPE html>
<html>
<body>

<p></p>

<script type='text/javascript'>
  document.getElementsByTagName('P')[0].innerHTML = 'something';

</script>
</body>
</html>

I get the desired result in any HTML / JAVASCRIPT interpreter but when I try to test it out in the extension the DOM manipulation isn't working. The p element isn't populated with 'something'. The manifest.json file is included in the extension folder I'm just not including it here as it's not relevant to the question.

How should I go about this ?

Update:

window.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <link rel='stylesheet' href='window.css'>

  </head>

<body>
<div><p></p></div>

<script src="window.js"></script>
</body>
</html>

window.js:

window.onload() {
  document.getElementsByTagName('P')[0].innerHTML = 'hakuna matata';
};
mr_incredible
  • 837
  • 2
  • 8
  • 21
  • This is off-topic from your question, but `document.getElementsByTagName('P')[0]` is just a terrible thing to do. [Here's why](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474). Also, don't use `.innerHTML` when you are getting/setting content that doesn't include any actual HTML. Instead, use `.textContent`. Lastly `type="text/javascript"` hasn't been needed in a `script` tag for about 5 years. – Scott Marcus Sep 30 '19 at 00:39
  • Also (FYI), your code is not "parsing" anything. It's attempting to set a property value. ["Parsing"](https://developer.mozilla.org/en-US/docs/Glossary/Parse) is the process of moving through a value (usually a string) to evaluate the contents of that value with the goal of transforming it into something else. – Scott Marcus Sep 30 '19 at 00:45

1 Answers1

0

You should import the JavaScript function using <script> tag like below:

In myfunction.js file of js folder:

document.getElementsByTagName('p')[0].innerHTML = 'something';

In html file:

<!DOCTYPE html>
<html>
  <body>
    <p></p>
    <script src="js/myfunction.js"></script>
  </body>
</html>

I tested it in Edge extension: If we use the JavaScript function directly in the html page then it doesn't work. If we use a link to the js file then it works.

Yu Zhou
  • 11,532
  • 1
  • 8
  • 22