Safe Browser and the Fetch API

Woot - I just tested my app with the new Safe Browser v0.2.1 and everything seems to be working. Nice to know that Polymer and Web Components will work fine in the Safe Browser.

I got one error using the Fetch API to load a resource file. I am not sure how to fix. Any suggestions?

Fetch API cannot load safe://nebnotes.arsnebula/locales/en.json. URL scheme "safe" is not supported.

2 Likes

Hi @arsnebula, can you please share the code that’s failing for you?

Sure. The app source itself is a lof of Polymer web components, but the offending code is just a standard fetch.

let url = 'safe://nebnotes.arsnebula/locales/en.json'
fetch(url).then( (res) => {
  return res.json()
}).then( (resources) => {
  console.log(resources)
}).catch( (error) => {
  console.log(error)
})

Here is a minimal Gist to reproduce the problem - https://gist.github.com/chrismbeckett/c7f464ffb1a730f086b9a72faedfb206

1 Like

You need to use the API under window.safe*, look at the complete documentation here: http://docs.maidsafe.net/beaker-plugin-safe-app, and the webFetch function is documented here: http://docs.maidsafe.net/beaker-plugin-safe-app/#windowsafeappwebfetch

You can take a look at the snippets to understand how to connect to the network here in this doc: SAFE Network API - Getting started (draft)

E.g., you can do something like this after you connected to the network (for browsing the web you don’t need to authorise you app, just initialise the library with window.safeApp.initialise and then connect with window.safeApp.connect):

window.safeApp.webFetch(
  appToken, // the app token obtained when invoking `initialise`
  'safe://nebnotes.arsnebula/locales/en.json' // the SAFE Network URL
)
.then((data) => {
   console.log('Web page content retrieved: ', data.toString());
});
2 Likes

That’s great info, thank you for the detailed response. I will give that a try this week as I start to integrate the Safe API into my app.

FYI - a standard XMLHttpRequest also works fine (as long as the file is published public with the rest of the website). It seems like this is an issue with the SAFE Browser support for the Fetch API.

let fetchJson = (path) => {
  return new Promise( (resolve, reject) => {
    let req = new XMLHttpRequest()
    req.onload = function(e) {
      if (req.status === 200) {
        resolve(JSON.parse(req.responseText))
      } else {
        reject(this.req.statusText)
      }
    }
    req.open('GET', path, true)
    req.send()
  })
}

fetchJson('resource.json').then( (data) => {
  console.log(data)
})
2 Likes

This topic was automatically closed after 60 days. New replies are no longer allowed.