Home > Net >  difference between open index.html and live server
difference between open index.html and live server

Time:09-27

I am trying to manipulate the SVG file based on this post document.getElementById results in null where moving svg into object tag and below are my files.

index.html

<body>
  <object data="../svg/barplot.svg" alt='bar-graph' type="image/svg xml" id="barplot" width="800"
    height="800">
  </object>
</body>

script.js

window.addEventListener("load", function () {
    var barplot = document.getElementById("barplot");
    console.log(barplot);
    var svgDoc = barplot.contentDocument;
    console.log(svgDoc);

When I use the VS Code live server, the output of svgDoc is the SVG file itself and everything works perferct.

Live server (barplot)

<object data="../svg/barplot.svg" alt="bar-graph" type="image/svg xml" id="barplot" width="800" height="800">
  </object>

Live server (svgDoc)

#document
<svg>
svg content
</svg>

However, if I use open index.html in the terminal and open the HTML file from the filesystem in a browser, the console output of svgDoc is null.

Open index.html (barplot)

<object data="../svg/barplot.svg" alt="bar-graph" type="image/svg xml" id="barplot" width="800" height="800">
  </object>

Open index.html (svgDoc)

null

For future development, I have to use the open index.html method. Could someone help with this issue? Thanks

CodePudding user response:

Opening a website locally and with a server has its differences.
In local you are really restricted in what you can do or access since it is affected by CORS.
And it seems this case is one of them.
You can't access the document that is being served by the filesystem.
Things like XMLHttpRequest or Fetch API are restricted too, you won't be able to request a local file with those. Or get the image data of a image drawn on a canvas.

CodePudding user response:

Opening with Live server means that you are serving all of your files locally on a "live-server" (your machine).

When you are opening index.html you are just viewing the static html page without the other files in your project. This is why your svg element is showing as null.

  • Related