Search code examples
javascripthtmlurlgithub-pages

GitHub pages relative links not working as intended


I'm working on this project, repo here. I'm trying to implement a random project button/link which is meant to redirect a viewer to a randomly selected page. I got that working (code in nav.js, links array in random-project-links-array.js) on localhost, but once I upload it on GitHub the links stop working. I guess it's an issue with relative links but I don't quite know how to fix it.

As far as I was able to see, when clicking the link, it gets redirected to username.github.io/project.subfolder.name/index.html with the repository folder name missing. As a result I get a 404.

When I click it from within a subfolder/project I get

Loading failed for the module with source “https://username.github.io/nav.js”.

and

Loading module from “https://username.github.io/nav.js” was blocked because of a disallowed MIME type (“text/html”).

If I manually change the URL in the browser, by adding the repo name where it should be, I get redirected to the proper page.

I guess I need a way to put the repository name in the link when redirecting to a different page but I don't want to hard code it as I want it to work both on localhost and deployed on GitHub pages.

I read about base URLs but I've never used them before so I don't know how to implement one.

I tried concatenating a window.location, trying to get the location.origin and adding the link, but for some reason when fetching the origin I get it with /index.html which creates a link along the lines of host/index.html/link-which-ends-in-.html.

I also tried adding a .nojekyll file to the project - no effect.

Bottom line is I'm trying to find a way to generate a link that starts with username.github.io/{repo.name} and add the second half of the link which redirects to the index.html page of a particular project.


Solution

  • I managed to figure it out. There were two issues - relative URLs weren't written properly and I kept missing the fact that projects were one level lower than the main hub.

    As such, I combed the project and rewrote URLs. Furthermore, to make the project work on local as well as GitHub, I edited the URLs in the array. I added a check for local host/different host and changed anchor href based on that. I added an extra check for the main hub based on location.href length and went up only one level when adding the 2nd half of the URL.

    It may not be the best solution but it got the job done without having to rework the entire project. Issue solved!