1
votes

I'd like to shorten my URL's using the Firebase Dynamic Link shortener. I followed the Rest API reference and the code seems to check out:

const url ="https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY";

this.request = new XMLHttpRequest();
this.request.open("GET", url, true);
this.request.setRequestHeader("Content-Type", "application/json");
this.request.setRequestHeader("Access-Control-Allow-Origin", "*");

const parameters = {
    "longDynamicLink": encodeURIComponent(window.location)
  };

this.request.onreadystatechange = this.updateLink;
this.request.send(parameters);

But when I execute this code, I get a CORS error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I can't seem to find a setting where I can enable Cross Origin Requests. Anyone who can tell me how to use Firebase Dynamic Links from the browser?

1

1 Answers

1
votes

I solved this problem by just creating a PHP script that I can use to delegate the Firebase Rest call from client-side to server-side. This also ensures my users will never get to see my Firebase API key.

<?php
$LongDynamicLink = "MYHOST?" . urlencode($_GET["url"]);
$url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY";
$data = '{
    "dynamicLinkInfo": {
      "dynamicLinkDomain": "MY_LINK_DOMAIN",
      "link": "' . $LongDynamicLink . '",
      "androidInfo": {
        "androidPackageName": "ANDROID_PACKAGE_NAME"
      },
      "iosInfo": {
        "iosBundleId": "IOS_BUNDLE_NAME"
      }
    }
  }';
echo httpPost($url, $data);
function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}
?>

Using this code, you can call the PHP Rest API as such:

let request = new XMLHttpRequest();
request.open("GET", "MY_DOMAIN/?url=URL_I_WANT_TO_SHORTEN", true);
request.onreadystatechange = console.log(request.response);
request.send();