Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

DaveTheBrave

Safari and file:// protocol

Power Mac G4

Posted on Nov 7, 2006 10:26 AM

Loading page content

Page content loaded

Niel

Nov 7, 2006 3:38 PM in response to DaveTheBrave

Nov 8, 2006 6:59 AM in response to Niel

m.Sharp

Nov 21, 2006 2:23 AM in response to DaveTheBrave

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

OS Integration

Web apps have a big reach. They run on multiple platforms. They are easy to share via links. But traditionally they lacked integration with the operating system. Not long ago they were not even installable. Luckily that has changed and now we can take advantage of that integration to add useful features to our PWAs. Let's explore some of those options.

Working with the file system

A typical user workflow using files looks like this:

  • Pick a file or folder from the device and open it directly.
  • Make changes to those files or folders, and save the changes back directly.
  • Make new files and folders.

Before the File System Access API , web apps couldn't do this. Opening files required a file upload, saving changes required users to download them, and the web had no access at all to make new files and folders in the user's filesystem.

Opening a file

To open a file we use the window.showOpenFilePicker() method. Note that this method requires a user gesture, such as a button click. Here is the rest of the setup for opening a file:

  • Capture the file handle from the file system access's file picker API. This gives you basic information about the file.
  • Using the handle's getFile() method, you'll get a special kind of Blob called a File that includes additional read-only properties (such as name and last modified date) about the file. Because it's a Blob, Blob methods can be called on it, such as text() , to get its content.

Saving changes

To save changes to a file, you also need a user gesture; then:

  • Use the file handle to create a FileSystemWritableFileStream .
  • Make changes to the stream. This won't update the file in place; instead, a temporary file is typically created.
  • Finally, when you've finished making changes, you close the stream, which moves the changes from temporary to permanent.

Let's see this in code:

File handling

The File System Access API lets you open files from within your app, but what about the other way around? Users want to set their favorite app as their default to open files with. The file handling API is an experimental API that lets installed PWAs: Register as a file handler on a user's device, specifying the MIME type and file extension that your PWA supports in your web app manifest. You can specify custom file icons for your supported extensions.

Once registered, your installed PWA will show up as an option from the user's file system, allowing them to open the file directly into it. Here is an example of the manifest setup for a PWA to read text files:

URL handling

With URL handling, your PWA can capture links that are part of its scope from the operating system and render them within a PWA window, instead of the default browser's tab. For example, if you receive a message linking to the PWA, or click on a deep link (a URL that points to a specific piece of content) in your PWA, the content will open in a standalone window.

This behavior is automatically available on Android when WebAPK is used, such as when users install a PWA with Chrome. It's impossible to capture URLs on PWAs installed on iOS and iPadOS from Safari.

For desktop browsers, the web browser community created a new spec. This spec is currently experimental ; it adds a new manifest file member: url_handlers . This property expects an array of origins that the PWA wants to capture. The origin of your PWA will be granted automatically, and each other origin must accept that handling operating through a file named web-app-origin-association . For example, if your PWA's manifest is hosted on the web.dev, and you want to add the app.web.dev origin, it would look like this:

In this case, the browser will check if a file exists at app.web.dev/.well-known/web-app-origin-association , accepting the URL handling from the PWA scope URL. The developer has to create this file. In the following example, the file looks like this:

URL protocol handling

URL handling works with standard https protocol URLs, but it is possible to use custom URI-schemes, such as pwa:// . In several operating systems, installed apps gain this ability by apps registering their schemes.

For PWA, this capability is enabled using the URL protocol handler API , available only on desktop devices. You can only allow custom protocols for mobile devices by distributing your PWA on app stores.

To register, you can use the registerProtocolHandler() method , or use the protocol_handlers member in your manifest, with the desired scheme and the URL you want to load in your PWA's context, such as:

You can route the URL from-protocol to the correct handler and get the query string value in your PWA. The %s is a placeholder for the escaped URL that triggered the operation, so if you have a link somewhere such as <a href="web+pwa://testing"> , your PWA will open /from-protocol?value=testing .

Calling other apps

You can use URI schemes to connect to any other installed app (PWA or not) in users' devices on every platform. You just need to create a link or use navigator.href and point to the URI scheme you want, passing the arguments in URL-escaped form.

You can use well known standard schemes, such as tel: for phone calls, mailto: for email sending, or sms: for text messaging; or you can learn about other apps' URL schemes, for example from well known messaging, maps, navigation, online meetings, social networks, and app stores.

Browser Support

With the Web Share API , your PWA can send content to other installed apps in the device through the shared channel.

The API is only available on operating systems with a share mechanism, including Android, iOS, iPadOS, Windows, and ChromeOS. You can share an object containing:

  • Text ( title and text properties)
  • A URL ( url property)
  • Files ( files property).

To check if the current device can share, for simple data, like text, you check for the presence of the navigator.share() method, to share files you check for the presence of the navigator.canShare() method.

You request the share action by calling navigator.share(objectToShare) . That call returns a Promise that resolves with undefined or rejects with an exception.

Chrome on Android and Safari on iOS opening the Share Sheet thanks to Web Share.

Web Share Target

Web Share Target API lets your PWA be a target of a share operation from another app on that device whether it is a PWA or not. Your PWA receives the data shared by another app.

It's currently available on Android with WebAPK and ChromeOS, and it works only after the user has installed your PWA. The browser registers the share target within the operating system when the app is installed.

You set up web share target in the manifest with the share_target member defined in the Web Share Target draft spec . share_target is set to an object with some properties:

For example, you can define for your PWA that you want to receive shared data (title and url only) by adding in your manifest:

From the previous sample, if any app in the system is sharing a URL with a title, and the user picks your PWA from the dialog, the browser will create a new navigation to your origin's /receive-share/?shared_title=AAA&shared_url=BBB , where AAA is the shared title, and BBB is the shared URL. You can use JavaScript to read that data from the window.location string by parsing it with the URL constructor .

The browser will use the PWA name and icon from your manifest to feed the operating system's share entry. You can't pick a different set for that purpose.

For more detailed examples and how to receive files, check Receiving shared data with the Web Share Target API

Contact Picker

With the Contact Picker API , you can request the device to render a native dialog with all the user's contacts so the user can choose one or more. Your PWA can then receive the data you want from those contacts.

The Contact Picker API is mainly available on mobile devices, and everything is done through the navigator.contacts interface on compatible platforms.

You can request the available properties to query with navigator.contacts.getProperties() , and request a single or multiple contact selection with a list of desired properties.

Some sample properties are name , email , address , and tel . When you ask the user to pick one or more contacts, you can call navigator.contacts.select(properties) , passing an array of properties you want to get in return.

The following sample will list the contacts received by the picker.

  • The File System Access API: simplifying access to local files
  • Let installed web applications be file handlers
  • Handle files in Progressive Web Apps
  • Integrate with the OS Sharing UI with the Web Share API
  • Share content with other apps
  • Receiving shared data with the Web Share Target API
  • A contact picker for the web

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2022-04-15 UTC.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

File System API

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers .

Note: This feature is available in Web Workers .

The File System API — with extensions provided via the File System Access API to access files on the device file system — allows read, write and file management capabilities.

Concepts and Usage

This API allows interaction with files on a user's local device, or on a user-accessible network file system. Core functionality of this API includes reading files, writing or saving files, and access to directory structure.

Most of the interaction with files and directories is accomplished through handles. A parent FileSystemHandle class helps define two child classes: FileSystemFileHandle and FileSystemDirectoryHandle , for files and directories respectively.

The handles represent a file or directory on the user's system. You can first gain access to them by showing the user a file or directory picker using methods such as window.showOpenFilePicker() and window.showDirectoryPicker() . Once these are called, the file picker presents itself and the user selects either a file or directory. Once this happens successfully, a handle is returned.

You can also gain access to file handles via:

  • The DataTransferItem.getAsFileSystemHandle() method of the HTML Drag and Drop API .
  • The File Handling API .

Each handle provides its own functionality and there are a few differences depending on which one you are using (see the interfaces section for specific details). You then can access file data, or information (including children) of the directory selected. This API opens up potential functionality the web has been lacking. Still, security has been of utmost concern when designing the API, and access to file/directory data is disallowed unless the user specifically permits it (note that this is not the case with the Origin private file system , because it is not visible to the user).

Note: The different exceptions that can be thrown when using the features of this API are listed on relevant pages as defined in the spec. However, the situation is made more complex by the interaction of the API and the underlying operating system. A proposal has been made to list the error mappings in the spec , which includes useful related information.

Note: Objects based on FileSystemHandle can also be serialized into an IndexedDB database instance, or transferred via postMessage() .

Origin private file system

The origin private file system (OPFS) is a storage endpoint provided as part of the File System API, which is private to the origin of the page and not visible to the user like the regular file system. It provides access to a special kind of file that is highly optimized for performance and offers in-place write access to its content.

Read our Origin private file system for instructions on how to use it.

Saving files

  • In the case of the asynchronous handles, use the FileSystemWritableFileStream interface. Once the data you'd like to save is in a format of Blob , String object, string literal or buffer , you can open a stream and save the data to a file. This can be the existing file or a new file.
  • In the case of the synchronous FileSystemSyncAccessHandle , you write changes to a file using the write() method. You can optionally also call flush() if you need the changes committed to disk at a specific time (otherwise you can leave the underlying operating system to handle this when it sees fit, which should be OK in most cases).

The FileSystemHandle interface is an object which represents an entry. Multiple handles can represent the same entry. For the most part you do not work with FileSystemHandle directly but rather its child interfaces FileSystemFileHandle and FileSystemDirectoryHandle .

Provides a handle to a file system entry.

provides a handle to a file system directory.

Provides a synchronous handle to a file system entry, which operates in-place on a single file on disk. The synchronous nature of the file reads and writes allows for higher performance for critical methods in contexts where asynchronous operations come with high overhead, e.g., WebAssembly . This class is only accessible inside dedicated Web Workers for files within the origin private file system .

is a WritableStream object with additional convenience methods, which operates on a single file on disk.

Accessing files

The below code allows the user to choose a file from the file picker.

The following asynchronous function presents a file picker and once a file is chosen, uses the getFile() method to retrieve the contents.

Accessing directories

The following example returns a directory handle with the specified name. If the directory does not exist, it is created.

The following asynchronous function uses resolve() to find the path to a chosen file, relative to a specified directory handle.

Writing to files

The following asynchronous function opens the save file picker, which returns a FileSystemFileHandle once a file is selected. A writable stream is then created using the FileSystemFileHandle.createWritable() method.

A user defined Blob is then written to the stream which is subsequently closed.

The following show different examples of options that can be passed into the write() method.

Synchronously reading and writing files in OPFS

This example synchronously reads and writes a file to the origin private file system .

The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:

  • Creates a synchronous file access handle.
  • Gets the size of the file and creates an ArrayBuffer to contain it.
  • Reads the file contents into the buffer.
  • Encodes the message and writes it to the end of the file.
  • Persists the changes to disk and closes the access handle.

Note: In earlier versions of the spec, close() , flush() , getSize() , and truncate() were unergonomically specified as asynchronous methods. This has now been amended , but some browsers still support the asynchronous versions.

Specifications

Browser compatibility, api.filesystemhandle.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

api.FileSystemFileHandle

Api.filesystemdirectoryhandle, api.filesystemwritablefilestream, api.filesystemsyncaccesshandle.

  • The File System Access API: simplifying access to local files on web.dev
  • The origin private file system on web.dev

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

local .pac-file URL format that works with IE and Safari (Windows)?

Say I want to use a proxy auto-config file that is stored at C:\proxy.pac. To make Internet Explorer use this configuration I have to specify the pac-file in the LAN settings in the following way:

But Safari, that uses the same proxy settings, will ignore it in this case. To make Safari use the pac-file I have to reference it as

(3 slashes at the beginning) which, according to Wikipedia is the correct format. But this way Internet Explorer will ignore it. Opera and Chrome, that also use the same proxy settings, are fine with both ways but is there another option that will work with Safari and Internet Explorer at the same time?

  • internet-explorer

FiveO's user avatar

  • I use a GitHub Gist as my proxy configuration file. (I know this is not "local", which is why I post this as a comment, not an answer.) –  bers May 11, 2022 at 7:50

5 Answers 5

For IE and the windows platform, the correct location for a local pac file seems to be:

next to your hosts file.

Gareth's user avatar

  • 4 please note there is no extension –  j040p3d20 Feb 13, 2011 at 12:48

This feature is no longer supported in W8.1 since the file:// schema was never supported by WinHTTP. So tools that use WinHTTP for proxy settings will not recognize it.

In November 2012, the .NET Framework was changed to use WinHTTP for PAC processing, which means that, by default, .NET Applications will not support file:// -based proxy scripts any longer either.

If you want to enable the file protocol for later version than IE10 you can always use the following registry setting:

  • Key: HKLM\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\
  • Value: EnableLegacyAutoProxyFeatures
  • Type: REG_DWORD

See section "NOTE: File://-based Proxy Scripts Deprecated" here .

0xC0000022L's user avatar

  • Your workaround does not work for IE/Edge on Windows 10, see superuser.com/a/1569042/253137 –  bers Jul 16, 2020 at 6:38

What happens if you use the dot, as Wikipedia also discusses: file://./C:/proxy.pac ? So long as it is not on a sharename, this "spelling" of the path might be acceptable to both IE and Safari.

Alternatively, run a local webserver and serve the .pac file, then provide the URL as http://localhost/path/to/proxy.pac . That should work around the differences in path URL formats by avoiding using a path URL entirely.

Jeremy W. Sherman's user avatar

On Windows 10, IE/Edge do not support reading a PAC file defined through the file:// syntax, even with EnableLegacyAutoProxyFeatures turned on:

This issue occurs because Internet Explorer and Edge on Windows 10-based computers use the WinHttp proxy service to retrieve proxy server information. The WinHttp Proxy service does not support using the ftp:// or file:// protocol for a PAC file. ( https://support.microsoft.com/help/4025058/ )

Since the same is true for .NET applications ( https://superuser.com/a/826013/253137 and https://blogs.msdn.microsoft.com/ieinternals/2013/10/11/understanding-web-proxy-configuration/ ), the range of application you can target with file:// syntax is rather slim.

bers's user avatar

If you have a local webserver running, you can deliver the local pac file through that webserver.

I.e. for IIS:

  • Place the file here: C:\inetpub\wwwroot\proxy.pac

enter image description here

  • Reference the PAC file in your proxy settings as: http://localhost/proxy.pac

Jpsy's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged windows proxy internet-explorer safari ..

  • The Overflow Blog
  • How to succeed as a data engineer without the burnout
  • How do you evaluate an LLM? Try an LLM.
  • Featured on Meta
  • New Focus Styles & Updated Styling for Button Groups
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network
  • Google Cloud will be Sponsoring Super User SE

Hot Network Questions

  • What are some simple problems that calculators get wrong?
  • Ambiguous stroke order/count for 離?
  • Help with Apex Class and Test Class
  • How do Biblical inerrantists explain disagreements about the interpretation of the Bible?
  • Does AI-based trading assume efficient market hypothesis?
  • Does Hippolyta love Theseus in Shakespeare's "A Midsummer Night's Dream?"
  • Ubuntu Jammy (in WSL): adding armhf arch, can't find packages or repositories
  • Stack - implementation in Java
  • Coauthorship of a paper with big name prof
  • What are some tracing disassemblers for the Z80
  • “Choose Your Own Adventure” with time travel and some very bizarre scenes in it from the 1980s or early 1990s
  • understanding logarithmic scale in a graph
  • What animals would herbivorous humans most likely domesticate?
  • Will SpaceX ever make a Heavy version of Starship Super Heavy
  • How does HTTP Keepalive handle multiple requests along with EOF from same origin?
  • What options do I have for latex-free interior house paint?
  • Is the principle of uniformity of nature an abduction or an analogy?
  • Situation with Artemov's paper?
  • RTC super capacitor is discharging very fast
  • Big-M in model notation?
  • Didn't dig a wide enough hole for a tree sapling. How do I fix?
  • What connectors to use for under cabinet lights?
  • Where does "excess" energy go when a vehicle uses a lower gear to move at a given speed?
  • How do Christians address the "Bigfoot" analogy presented by skeptics in relation to the resurrection of Jesus?

safari file protocol

Abusing Safari's webarchive file format

  • Apr 25, 2013

Last updated at Tue, 16 Jan 2024 16:26:37 GMT

tldr: For now, don't open .webarchive files, and check the Metasploit module, Apple Safari .webarchive File Format UXSS

Safari's webarchive format saves all the resources in a web page - images, scripts, stylesheets - into a single file. A flaw exists in the security model behind webarchives that allows us to execute script in the context of any domain (a Universal Cross-site Scripting bug). In order to exploit this vulnerability, an attacker must somehow deliver the webarchive file to the victim and have the victim manually open it 1 (e.g. through email or a forced download), after ignoring a potential "this content was downloaded from a webpage" warning message 2 .

It is easy to reproduce this vulnerability on any Safari browser: Simply go to https://browserscan.rapid7.com/ (or any website that uses cookies), and select File -> Save As... and save the webarchive to your ~/Desktop as metasploit.webarchive. Now convert it from a binary plist to an XML document (on OSX):

Open up ~/Desktop/metasploit_xml.webarchive in your favorite text editor. Paste the following line (base64 for

) at the top of the first large base64 block.

safari file protocol

Now save the file and double click it from Finder to open in Safari:

safari file protocol

You will see your browserscan.rapid7.com cookies in an alert box. Using this same approach, an attacker can send you crafted webarchives that, upon being opened by the user, will send cookies and saved passwords back to the attacker. By modifying the WebResourceURL key, we can write script that executes in the context of any domain, which is why this counts as a UXSS bug.

Unfortunately, Apple has labeled this a "wontfix" since the webarchives must be downloaded and manually opened by the client. This is a potentially dangerous decision, since a user expects better security around the confidential details stored in the browser, and since the webarchive format is otherwise quite useful. Also, not fixing this leaves only the browser's file:// URL redirect protection, which has been bypassed many times in the past .

Let's see how we can abuse this vulnerability by attempting to attack browserscan.rapid7.com :

Attack Vector #1: Steal the user's cookies. Straightforward. In the context of https://browserscan.rapid7.com/ , simply send the attacker back the document.cookie . HTTP-only cookies make this attack vector far less useful.

Attack Vector #2: Steal CSRF tokens. Force the browser to perform an AJAX fetch of https://browserscan.rapid7.com and send the response header and body back to the attacker.

Attack Vector #3: Steal local files. Since .webarchives must be run in the file:// URL scheme, we can fetch the contents of local files by placing AJAX requests to file:// URLs 3 . Unfortunately, the tilde (~) cannot be used in file:// URLs, so unless we know the user's account name we will not be able to access the user's home directory. However this is easy to work around by fetching and parsing a few known system logs 4 from there, the usernames can be parsed out and the attacker can start stealing known local file paths (like /Users/username/.ssh/id_rsa) and can even "crawl" for sensitive user files by recursively parsing .DS_Store files in predictable locations (OSX only) 5 .

Attack Vector #4: Steal saved form passwords. Inject a javascript snippet that, when the page is loaded, dynamically creates an iframe to a page on an external domain that contains a form (probably a login form). After waiting a moment for Safari's password autofill to kick in, the script then reads the values of all the input fields in the DOM and sends it back to the attacker 6 .

Attack Vector #5: Store poisoned javascript in the user's cache. This allows for installing “viruses” like persisted keyloggers on specific sites... VERY BAD! An attacker can store javascript in the user's cache that is run everytime the user visits https://browserscan.rapid7.com/ or any other page under browserscan.rapid7.com that references the poisoned javascript. Many popular websites cache their script assets to conserve bandwidth. In a nightmare scenario, the user could be typing emails into a "bugged" webmail, social media, or chat application for years before either 1) he clears his cache, or 2) the cached version in his browser is expired. Other useful assets to poison are CDN-hosted open-source JS libs like google's hosted jquery, since these are used throughout millions of different domains.

Want to try for yourself? I've written a Metasploit module that can generate a malicious .webarchive that discretely carries out all of the above attacks on a user-specified list of URLs. It then runs a listener that prints stolen data on your msfconsole.

Unless otherwise noted, all of these vectors are applicable on all versions of Safari on OSX and Windows.

Disclosure Timeline

file:///var/log/install.log file:///var/log/system.log file:///var/log/secure.log

file:///Users/username/Documents/.DS_Store file:///Users/username/Pictures/.DS_Store file:///Users/username/Desktop/.DS_Store

X-Frame-Options can be used to disable loading a page in an iframe, but does not necessarily prevent against UXSS attacks stealing saved passwords. You can always attempt to pop open a new window to render the login page in. If popups are blocked, Flash can be used to trivially bypass the blocker, otherwise you can coerce the user to click a link.

SHARING IS CARING

  • Metasploit   (622)
  • Vulnerability Management   (339)
  • Research   (232)
  • Detection and Response   (196)
  • Vulnerability Disclosure   (145)
  • Cloud Security   (135)
  • Emergent Threat Response   (128)
  • Security Operations   (20)

Popular Tags

  • Metasploit Weekly Wrapup
  • Vulnerability Management

Related Posts

XSS in JSON: Old-School Attacks for Modern Applications

Metasploit Weekly Wrap-Up: Mar. 4, 2022

The Everyperson’s Guide to Log4Shell (CVE-2021-44228)

Metasploit Wrap-Up 12/10/21

Never miss a blog

Get the latest stories, expertise, and news about security today.

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

The ultimate guide to enabling Cross-Origin Resource Sharing (CORS)

safari file protocol

Consider the following situation: you’re trying to fetch some data from an API on your website using fetch() but end up with an error.

Guide to Cross-origin-sharing CORS

You open up the console and see either “No Access-Control-Allow-Origin header is present on the requested resource,” or “The Access-Control-Allow-Origin header has a value <some_url> that is not equal to the supplied origin” written in red text, indicating that your request was blocked by CORS policy.

Blocked Request due to CORS

Seem familiar? With over 10,000 questions posted under the cors tag on StackOverflow, it is one of the most common issues that plague frontend developers and backend developers alike. So, what exactly is the CORS policy and why do we face this error often?

What is Cross-Origin Resource Sharing (CORS)?

Interestingly, this is not an error as we portray it, but rather the expected behavior. Our web browsers enforce the same-origin policy , which restricts resource sharing across different origins. Cross-origin resource sharing , or CORS, is the mechanism through which we can overcome this barrier. To understand CORS, let us first understand the same-origin policy and its need.

The same-origin policy

In simple terms, the same-origin policy is the web version of “don’t talk to strangers” incorporated by the browser.

All modern web browsers available today follow the same-origin policy that restricts how XMLHttpRequest and fetch requests from one origin interact with a resource from another origin. What’s an origin, exactly?

It’s the combination of a scheme, domain, and port. The scheme could be HTTP, HTTPS, FTP, or anything else. Similarly, the port can also be any valid port number. Same-origin requests are essentially those requests whose scheme, domain, and port match. Let’s look at the following example.

Assuming our origin is http://localhost:3000 , the requests can be categorized into same-origin or cross-origin requests as follows:

This is the reason why your frontend running on http://localhost:3000 cannot make API calls to your server running http://localhost:5000 or any other port when you develop single-page applications (SPAs).

Also, requests from origin https://mywebsite.com to origin https://api.mywebsite.com are still considered cross-site requests even though the second origin is a subdomain.

Due to the same-origin policy, the browser will automatically prevent responses from cross-origin requests from being shared with the client. This is great for security reasons! But not all websites are malicious and there are multiple scenarios in which you might need to fetch data from different origins, especially in the modern age of microservice architecture where different applications are hosted on different origins.

This is a great segue for us to deep dive into CORS and learn how to use it in order to allow cross-origin requests.

Allowing cross-site requests with CORS

We’ve established that the browser doesn’t allow resource sharing between different origins, yet there are countless examples where we are able to do so. How? This is where CORS comes into the picture.

CORS is an HTTP header-based protocol that enables resource sharing between different origins. Alongside the HTTP headers, CORS also relies on the browser’s preflight-flight request using the OPTIONS method for non-simple requests. More on simple and preflight requests later in this article.

Because HTTP headers are the crux of the CORS mechanism, let’s look at these headers and what each of them signifies.

Access-Control-Allow-Origin

The Access-Control-Allow-Origin response header is perhaps the most important HTTP header set by the CORS mechanism. The value of this header consists of origins that are allowed to access the resources. If this header is not present in the response headers, it means that CORS has not been set up on the server.

safari file protocol

Over 200k developers use LogRocket to create better digital experiences

safari file protocol

If this header is present, its value is checked against the Origin header of request headers. If the values match, the request will be completed successfully and resources will be shared. Upon mismatch, the browser will respond with a CORS error.

To allow all origins to access the resources in the case of a public API, the Access-Control-Allow-Origin header can be set to * on the server. In order to restrict only particular origins to access the resources, the header can be set to the complete domain of the client origin such as https://mywebsite.com .

Access-Control-Allow-Methods

The Access-Control-Allow-Methods response header is used to specify the allowed HTTP method or a list of HTTP methods such as GET , POST , and PUT that the server can respond to.

This header is present in the response to pre-flighted requests. If the HTTP method of your request is not present in this list of allowed methods, it will result in a CORS error. This is highly useful when you want to restrict users from modifying the data through POST , PUT , PATCH , or DELETE requests.

Access-Control-Allow-Headers

The Access-Control-Allow-Headers response header indicates the list of allowed HTTP headers that your request can have. To support custom headers such as x-auth-token , you can set up CORS on your server accordingly.

Requests that consist of other headers apart from the allowed headers will result in a CORS error. Similar to the Access-Control-Allow-Methods header, this header is used in response to pre-flighted requests.

Access-Control-Max-Age

Pre-flighted requests require the browser to first make a request to the server using the OPTIONS HTTP method. Only after this can the main request be made if it is deemed safe. However, making the OPTIONS call for each pre-flighted request can be expensive.

To prevent this, the server can respond with the Access-Control-Max-Age header, allowing the browser to cache the result of pre-flighted requests for a certain amount of time. The value of this header is the amount of time in terms of delta seconds.

More great articles from LogRocket:

  • Don't miss a moment with The Replay , a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Overall, here’s the syntax of how CORS response headers look like:

Simple requests vs. pre-flighted requests

Requests that do not trigger a CORS preflight fall under the category of simple requests. However, the request has to satisfy some conditions only after it is deemed as a simple request. These conditions are:

  • The HTTP method of the request should be one of these: GET , POST , or HEAD
  • The request headers should only consist of CORS safe-listed headers such as Accept , Accept-Language , Content-Language , and Content-Type apart from the headers automatically set by the user agent
  • The Content-Type header should have only either of these three values: application/x-www-form-urlencoded , multipart/form-data , or text/plain
  • No event listeners are registered on the object returned by the XMLHttpRequest.upload property if using XMLHttpRequest
  • No ReadableStream object should be used in the request

On failing to satisfy either of these conditions, the request is considered to be a pre-flighted request. For such requests, the browser has to first send a request using the OPTIONS method to the different origin.

This is used to check if the actual request is safe to send to the server. The approval or rejection of the actual request depends on the response headers to the pre-flighted request. If there is a mismatch between these response headers and the main request’s headers, the request is not made.

Enabling CORS

Let’s consider our initial situation where we faced the CORS error. There are multiple ways we could resolve this issue depending on whether we have access to the server on which the resources are hosted. We can narrow it down to two situations:

  • You have access to the backend or know the backend developer
  • You can manage only the frontend and cannot access the backend server

If you have access to the backend:

Because CORS is just an HTTP header-based mechanism, you can configure the server to respond with appropriate headers in order to enable resource sharing across different origins. Have a look at the CORS headers we discussed above and set the headers accordingly.

For Node.js + Express.js developers, you can install the cors middleware from npm. Here is a snippet that uses the Express web framework, along with the CORS middleware:

If you don’t pass an object consisting of CORS configuration, the default configuration will be used, which is equivalent to:

Here is how you could configure CORS on your server which will only allow GET requests from https://yourwebsite.com with headers Content-Type and Authorization with a 10 minutes preflight cache time:

While this code is specific to Express.js and Node.js, the concept remains the same. Using the programming language and framework of your choice, you can manually set the CORS headers with your responses or create a custom middleware for the same.

If you only have access to the frontend:

Quite often, we may not have access to the backend server. For example, a public API. Due to this, we cannot add headers to the response we receive. However, we could use a proxy server that will add the CORS headers to the proxied request.

The cors-anywhere project is a Node.js reverse proxy that can allow us to do the same. The proxy server is available on https://cors-anywhere.herokuapp.com/ , but you can build your own proxy server by cloning the repository and deploying it on a free platform like Heroku or any other desired platform.

In this method, instead of directly making the request to the server like this:

Simply append the proxy server’s URL to the start of the API’s URL, like so:

As we learn to appreciate the same-origin policy for its security against cross-site forgery attacks, CORS does seem to make a lot of sense. While the occurrences of the red CORS error messages in the console aren’t going to magically disappear, you are now equipped with the knowledge to tackle these messages irrespective of whether you work on the frontend or the backend.

Get set up with LogRocket's modern error tracking in minutes:

  • Visit https://logrocket.com/signup/ to get an app ID

Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, not server-side

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)

safari file protocol

Stop guessing about your digital experience with LogRocket

Recent posts:.

Using Aoi Js To Build A Bot For Discord

Using aoi.js to build a bot on Discord

Explore how the aoi.js library makes it easy to create Discord bots with useful functionalities for frontend applications.

safari file protocol

Web Components adoption guide: Overview, examples, and alternatives

Evaluate Web Components, a set of standards that allow you to create custom HTML tags for more reusable, manageable code.

safari file protocol

Using AWS Lambda and CloudFront to optimize image handling

Leverage services like AWS Lambda, CloudFront, and S3 to handle images more effectively, optimizing performance and providing a better UX.

safari file protocol

Building web-based terminal components with Termino.js

Explore Termino.js, an open source library for integrating web-based terminals into applications, in this introduction article.

safari file protocol

2 Replies to "The ultimate guide to enabling Cross-Origin Resource Sharing (CORS)"

In depth and finly captured.

I may have missed something but if we can kind of bypass the cors policy by just using cors-anywhere, what’s the point in using cors/setting up cors in the server anyway????

Leave a Reply Cancel reply

safari file protocol

Maintenance work is planned for Wednesday 1st May 2024 from 9:00am to 11:00am (BST).

During this time, the performance of our website may be affected - searches may run slowly and some pages may be temporarily unavailable. If this happens, please try refreshing your web browser or try waiting two to three minutes before trying again.

We apologise for any inconvenience this might cause and thank you for your patience.

safari file protocol

Chemical Communications

Cr-catalyzed borylation of c(aryl)–f bonds using terpyridine ligand.

The defluoroborylation of fluoroarenes by chromium-catalyzed cleavage of unactivated C–F bonds is described. The reaction uses HBpin as the boron source, low-cost and commercially available chromium salt as the precatalyst, and terpyridine as crucial ligand, providing a protocol with atom-efficient benefits and a wide range of applicable substrates for the functionalization of aryl C–F bonds. Preliminary mechanistic studies indicate an unprecedant Cr-catalyzed magnesation of unactivated C–F bond occurred. The generated arylmagnesium intermediates then participated in the subsequent borylation reaction. The application of the stratey in the preparation of valuable derivatives is demonstrated by the late-stage functionalization of boronate ester groups.

Supplementary files

  • Supplementary information PDF (10623K)

Article information

Download citation, permissions.

safari file protocol

S. Liu, Z. Luo, S. Zhao, M. Luo and X. Zeng, Chem. Commun. , 2024, Accepted Manuscript , DOI: 10.1039/D4CC01330A

To request permission to reproduce material from this article, please go to the Copyright Clearance Center request page .

If you are an author contributing to an RSC publication, you do not need to request permission provided correct acknowledgement is given.

If you are the author of this article, you do not need to request permission to reproduce figures and diagrams provided correct acknowledgement is given. If you want to reproduce the whole article in a third-party publication (excluding your thesis/dissertation for which permission is not required) please go to the Copyright Clearance Center request page .

Read more about how to correctly acknowledge RSC content .

Social activity

Search articles by author.

This article has not yet been cited.

Advertisements

IMAGES

  1. Mac용 Safari에서 다운로드한 파일을 찾는 위치 및 파일 관리 방법

    safari file protocol

  2. How to Change Where Safari Files Download in iOS

    safari file protocol

  3. How to Markup and Save as PDF in Safari iOS/iPadOS?

    safari file protocol

  4. How to use Safari private browsing on Mac, iPhone & iPad

    safari file protocol

  5. How to sort files by date in Safari file picker

    safari file protocol

  6. Viewing the HTML Source Code in Safari

    safari file protocol

VIDEO

  1. FTP (File Transfer Protocol), SFTP, TFTP Explained

  2. How to Fix the “Safari Can’t Establish a Secure Connection to the Server” Error (6 Solutions)

  3. What is FTP (File Transfer Protocol) and how do I use it?

  4. Using the Safari Console

  5. IPhone 5 Tips: Using Safari and Features

  6. What is Secure File Transfer Protocol ( SFTP )

COMMENTS

  1. Protocols supported by Safari browser

    But I don't know that by default which of them are opend by Safari web browser and not any third party application. safari; url-scheme; Share. Follow edited Jan 15, 2014 at 14:53. unor. 94.4k 27 27 ... Browser protocol handler options for ios. Related questions. 65 Check if URL scheme is supported in javascript. 78 ...

  2. About Apple URL Schemes

    About Apple URL Schemes. This document describes several URL schemes that are supported by system apps on iOS, macOS, and watchOS 2 and later. Native iOS apps and web apps running in Safari on any platform can use these schemes to integrate with system apps and provide a more seamless experience for the user.

  3. Changing Developer settings in Safari on macOS

    Disable local file restrictions. Disable security checks that may prohibit local development when loading content with the file:// protocol. Disable cross-origin restrictions. Disable security checks that are performed when loading resources from origins other than the one from which the main page was loaded.

  4. Safari and file:// protocol

    Safari will display a file that is written in a format it can understand in the browser window when it's address is entered into the Safari address bar. If you enter a folder address, Safari sends your request to the Finder instead of handling it itself. I forgot to mention I can enter the file://... string in the URL and the document appears ...

  5. How do I configure custom URL handlers on OS X?

    Launching External Applications using Custom Protocols under OSX. OS X URL handler to open links to local files. I get that you can tell the system that a particular program is able to handle a certain scheme / protocol with the Info.plist file: <key>CFBundleURLTypes</key>. <array>. <dict>. <key>CFBundleURLName</key>. <string>Local File</string>.

  6. About WebDriver for Safari

    WebDriver is a REST API. It hosts a local web server that accepts REST-style HTTP requests, so it can accept automation commands from a wide variety of test setups. To support WebDriver without sacrificing a user's privacy or security, Safari's driver provides extra safeguards to ensure that test execution is isolated from normal browsing ...

  7. Safari inserts "localhost" in URLs with three slashes after the scheme

    That is the protocol the browser uses to talk to other programs. The browser should adhere to it when doing that. But the interaction with the user happens on a different OSI level. ... So it appears that Safari considers three slashes as file URL scheme special case (empty string) and replaces empty string between second and third slash with ...

  8. OS Integration

    Caution: Safari implements the File System Access API, not for the public system, but as an origin-private sandbox. You can only read and write files in that virtual file system using this API. ... URL protocol handling. URL handling works with standard https protocol URLs, but it is possible to use custom URI-schemes, such as pwa://. In ...

  9. File System API

    This API allows interaction with files on a user's local device, or on a user-accessible network file system. Core functionality of this API includes reading files, writing or saving files, and access to directory structure. Most of the interaction with files and directories is accomplished through handles. A parent FileSystemHandle class helps ...

  10. proxy

    Say I want to use a proxy auto-config file that is stored at C:\proxy.pac. To make Internet Explorer use this configuration I have to specify the pac-file in the LAN settings in the following way: file://C:/proxy.pac But Safari, that uses the same proxy settings, will ignore it in this case. To make Safari use the pac-file I have to reference it as

  11. Abusing Safari's webarchive file format

    Attack Vector #3: Steal local files. Since .webarchives must be run in the file:// URL scheme, we can fetch the contents of local files by placing AJAX requests to file:// URLs3. Unfortunately, the tilde (~) cannot be used in file:// URLs, so unless we know the user's account name we will not be able to access the user's home directory.

  12. The ultimate guide to enabling Cross-Origin Resource Sharing (CORS)

    The Access-Control-Allow-Origin response header is perhaps the most important HTTP header set by the CORS mechanism. The value of this header consists of origins that are allowed to access the resources. If this header is not present in the response headers, it means that CORS has not been set up on the server.

  13. Enable local file access on Safari: iOS, iPhone, on iPad

    By default, Safari web browser doesn't allow access to local files. It is only possible if you already have enabled the Develop menu. To enable local file access on Safari: How to enable Safari local file access on a Mac? Open the Safari browser and click on Develop in the upper menu.

  14. Cr-catalyzed borylation of C(aryl)-F bonds using terpyridine ligand

    The defluoroborylation of fluoroarenes by chromium-catalyzed cleavage of unactivated C-F bonds is described. The reaction uses HBpin as the boron source, low-cost and commercially available chromium salt as the precatalyst, and terpyridine as crucial ligand, providing a protocol with atom-efficient benefits and a wide range of applicable substrates for the functionalization of aryl C-F bonds.

  15. Safari 17.2 Release Notes

    Fixed <a> and <area> protocol setters for non-parsable URLs. (114371380) Fixed URL's protocol setter to forbid change a special URL to a non-special URL. (114624048) ... When you only supply a transparent icon with custom shape, Safari automatically adjusts spacing between your icon and the standard system background to avoid tangents ...

  16. iOS Mobile Safari not liking the ftp:// protocol

    3. Try to type: ftp://username:password@host. This should work. Mobile Safari is a browser with limited functionality. Personally, i dislike it. It is good browser for web-surfing and stuff, but it's not very useful for developer. answered Sep 26, 2013 at 16:10. brotheroftux.

  17. PDF Draft Risk Evaluation for Asbestos Part 2

    2021 Draft Systematic Review Protocol, respectively (U.S. EPA, 2021). Data quality evaluations for all the references that met PECO screening criteria are included in the Draft Risk Evaluation for Asbestos Part 2 - Systematic Review Supplemental File: Data Quality Evaluation Information for General Population, Consumer, and Environmental Exposure

  18. Catalina Safari "Proxy Automatic Configuration" (PAC) is not used

    3. Running Catalina (10.15.6) My SOCKS5 proxy is a DynamicForward declared port on a ssh session. My pac file is ultra simple and tested good using online test tools, as well as Chrome which uses the OS's PAC setting. To eliminate a filesystem sandbox issue, I host the PAC file using a python SimpleHTTPServer.