简体   繁体   中英

Electron page navigation: Loading content and attached javascript

I am trying to create a basic page navigation in electron.

In the electron api demo import is used for that purpose(as far as I can understand it). Regarding the import I found the information that its deprecated and was removed from Chrome in February 2020.
As an alternative, the Node-module fs can be used. My problem: scripts are not loaded.

What is the best way to load content and attached javascript into a div?

Github Code:

Thanks to @Entertain the problem could solved. I have updated the Git-Repo.

Okay first of all, we are working with dynamic DOM elements. This means addEventListener is evaluated once and after you add new elements dynamically to your DOM, it won't be applied. This workaround in your winController.js will help:

// Hello.addEventListener("click", function () {
//   loadPage("./assets/html/Hello.html", "content");
// });

// Info.addEventListener("click", function () {
//   loadPage("./assets/html/Info.html", "content");
// });

// This implementation doesn't care whether an element with the given id exists
document.addEventListener('click', function (e) {
  if (e.target && e.target.id == 'Hello') {
    loadPage('./assets/html/Hello.html', 'content');
  } else if (e.target && e.target.id == 'Info') {
    loadPage('./assets/html/Info.html', 'content');
  }
});

Next remove the export in your functions.js file, it's not needed:

function thanks() {
  alert('Thanks');
}

The only thing left, and that is the most important one, is to update how we load the functions.js file dynamically:

<!-- <script type="module" src="../js/functions.js"></script> -->
<script type="module">
  let script = document.createElement('script');
  script.src = './assets/js/functions.js';
  document.head.append(script);
  
  // function thanks() {
  //     alert("Thanks");
  //   }
  Say.addEventListener('click', function () {
    thanks();
  });
</script>

And that's it, after this changes your alert should fire!

Edit: Rename your Hello.Html to Hello.html please, or event better write everything in lowercase in the future to prevent further mistakes: hello.html and info.html .

Notice: In your Info.html file your button has the wrong id:

<!-- <button type="submit" class="btn btn-success btn-lg mt-2" id="Info"> -->
<button type="submit" class="btn btn-success btn-lg mt-2" id="Hello">
  Jump to Hello
</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM