Search code examples
javascriptarraysurlforeachtemplate-literals

How can I create unique URL-s for sites generated from JS?


I have three buttons. I loop through the buttons with foreach and each button will open a new site with different contents, which are stored in an array (I filter through the array and put the value of the content keys in a variable):

let sites = [{
    "id": 1,
    "content": "Lorem ipsum 1"
  },
  {
    "id": 2,
    "content": "Lorem ipsum 2"
  },
  {
    "id": 3,
    "content": "Lorem ipsum 3"
  }
];

let siteLinks = document.querySelectorAll(".site-link");

siteLinks.forEach((el) => {
  el.addEventListener("click", () => {

    sites.filter((site) => {
      if (el.innerText == site.id) {
        var opened = window.open("", '_blank');
        opened.document.write(`
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project site</title>
    <link rel="stylesheet" href="css/styles.css">

</head>

<body>

<div class="content">
  ${site.content}
</div>

</body>

</html>`)
      }
    });
  });
});
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate sites from JS</title>
    <link rel="stylesheet" href="css/styles.css">
  </head>

  <body>
    <div class="btn-container">
      <button class="site-link">1</button>
      <button class="site-link">2</button>
      <button class="site-link">3</button>
    </div>
  </body>
</html>

The question is, how could I generate a unique URL for each opened site such as "www.site-domain.com/site-1.php", "www.site-domain.com/site-2.php", "www.site-domain.com/site-3.php" etc? Because now if a new site is opened I can see "about:blank" in the browser window. Thank you in advance for your help.


Solution

  • let sites = [{
        "id": 1,
        "content": "Lorem ipsum 1",
        "url": "http://example-1.com"
      },
      {
        "id": 2,
        "content": "Lorem ipsum 2",
        "url": "http://example-2.com"
      },
      {
        "id": 3,
        "content": "Lorem ipsum 3",
        "url": "http://example-3.com"
      }
    ];
    

    You can add url property as in example above with web-site address that you want, then you can add this property to window.open (first argument) following the example below:

    var opened = window.open(site.url, '_blank');