Get a canonical URL using JavaScript


I'm building a website internally and the page has a canonical URL set in the <head> that specifies the page's URL externally.

Is there any way to use JavaScript to obtain the canonical URL?

Something like this?

<!DOCTYPE html>
        <link href="" rel="canonical" />
        <script type="text/javascript">
            window.onload = function () {
                var canonical = "";
                var links = document.getElementsByTagName("link");
                for (var i = 0; i < links.length; i ++) {
                    if (links[i].getAttribute("rel") === "canonical") {
                        canonical = links[i].getAttribute("href")