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

MatsBeckman

html input type file don't work

I upgraded to Safari 14.0.1 (14610.2.11.51.10) in Mojave and suddenly html input type file tags stopped working. It seems to deny file access when the button is clicked. Why?

iMac 27″, macOS 10.14

Posted on Nov 21, 2020 2:39 AM

Similar questions

  • Safari on Mac converts sites to pages On Safari, when I click a link in a webpage, it always converts to a standalone read format doc, and I can click no more. 276 1
  • Apple web pages don't open in Safari Help! Ever since I updated my 15-inch mid-2012 Macbook Pro Retina to Catalina, I can't use Safari to open Apple web pages. Some pages have incorrect formatting, as if the style sheets aren't loading properly, and are unreadable and unusuable. Other pages simply get a "can't open page" error. I had to open Chrome to enter this question, in fact. What the hell? I mean . . . what the hell? 259 1
  • Command + L Not Working in Safari with Mac OS 11.6 update Command + L shortcut is not working in Safari with latest MacOS 11.6 update. Shortcut is working in Chrome browser. 867 1

Loading page content

Page content loaded

Nov 27, 2020 6:55 AM in response to MatsBeckman

seems like a bug in safari 14.0.1 on Mojave.

https://stackoverflow.com/questions/64843459/input-type-file-on-html-form-not-working-on-safari-version-14-0-1-14610-2-11-51

btw: for me, the solution to add an "accept"-attribute to the file-input didn't work.

  • Skip to main content
  • Select language
  • Skip to search

<input type="file">

Limiting accepted file types.

element is used to create interactive controls for web-based forms in order to accept data from the user." href="../input.html"> <input> elements with type="file" let the user pick one or more files, to upload to a server via form submission , or manipulated by JavaScript with the File API .

File inputs' value attribute contains a DOMString that represents the path to the selected file(s).

  • If multiple files are selected, the string represents the first selected file. JavaScript can access the other files through the input's FileList property .
  • If no file is yet selected, the string is "" (empty).
  • The string is prefixed with C:\fakepath\ , to prevent malicious software from guessing the user's file structure.

Using file inputs

A basic example.

This produces the following output:

Note : You can find this example on GitHub too — see the source code , and also see it running live .

Regardless of the user's device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file.

Including the multiple attribute, as shown above, specifies that multiple files can be chosen at once. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down Shift or Control , and then clicking). If you only want the user to choose a single file per <input> , omit the multiple attribute.

When the example is submitted, each selected file's name will be added to URL parameters in the following fashion: ?file=file1.txt&file=file2.txt

Getting information on selected files

The selected files' are returned by the element's HTMLInputElement.files property — this returns a element; this lets you access the list of files selected with the <input type="file"> element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage." href="../../../../DOM/FileList.html"> FileList object, which contains a list of File objects. The FileList behaves like an array, so you can check its length property to get the number of selected files.

Each File object contains the following information:

  • name : The file name.
  • lastModified : A number representing the date the file was last modified, as a UNIX timestamp.
  • lastModifiedDate : A Date object representing the date and time the file was last modified.
  • size : A number representing the size of the file in bytes.
  • type : A DOMString representing the MIME type of the file.

Often you won't want any type of file. For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as JPEG or PNG .

Acceptable file types can be specified with the accept attribute, which takes a comma-separated list of allowed file extensions or MIME types. Some examples:

  • accept="image/png" or accept=".png" — Accepts PNG files.
  • accept="image/png, image/jpeg" or accept=".png, .jpg, .jpeg" — Accept PNG or JPEG files.
  • accept="image/*" — Accept any file with an image/* MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.)
  • accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" — accept anything that smells like an MS Word document.

Let's look like a more complete example:

This produces a similar-looking output to the previous example:

It may look similar, but if you try selecting a file with this input, you'll see that the file picker only lets you select the file types specified in the accept value (the exact nature differs across browsers and operating systems).

Screenshot of a macOS file picker dialog. Files other than JPEG are grayed-out and unselectable.

The accept attribute doesn't validate the types of the selected files — it provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes all files selectable, and then choose incorrect file types.

Therefore, make sure that the accept attribute is backed up by appropriate server-side validation.

In this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the HTMLInputElement.files property, as well as showing off a few clever tricks.

Note : You can see the complete source code for this example on GitHub — file-example.html ( see it live also ). We won't explain the CSS; the JavaScript is the main focus.

First of all, let's look at the HTML:

This is similar to what we've seen before — nothing special to comment on.

Next, let's walk through the JavaScript.

In the first lines of script, we get references to the form input itself, and the element is the generic container for flow content and does not inherently represent anything. Use it to group elements for purposes such as styling (using the class or id attributes), marking a section of a document in a different language (using the lang attribute), and so on." href="../div.html"> <div> element with the class of .preview . Next, we hide the element is used to create interactive controls for web-based forms in order to accept data from the user." href="../input.html"> <input> element — we do this because file inputs tend to be ugly, difficult to style, and inconsistent in their design across browsers. You can activate the input element by clicking its element represents a caption for an item in a user interface." href="../label.html"> <label> , so it is better to visually hide the input and style the label like a button, so the user will know to interact with it if they want to upload files.

Note: opacity is used to hide the file input instead of visibility: hidden or display: none , because assistive technology interprets the latter two styles to mean the file input isn't interactive.

Next, we add an event listener to the input for when its selected value changes (in this case, when files are selected). The event listener invokes our custom updateImageDisplay() function.

Whenever the updateImageDisplay() function is invoked, we:

  • Use a while loop to empty the previous contents of the preview <div> .
  • Grab the element; this lets you access the list of files selected with the <input type="file"> element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage." href="../../../../DOM/FileList.html"> FileList object that contains the information on all the selected files, and store it in a variable called curFiles .
  • Check to see if no files were selected, by checking if curFiles.length is equal to 0. If so, print a message into the preview <div> stating that no files have been selected.
  • If files have been selected, we loop through each one, printing information about it into the preview <div> . Things to note here:
  • We use the custom validFileType() function to check whether the file is of the correct type (e.g. the image types specified in the accept attribute).
  • Print out its name and file size into a list item inside the previous <div> (obtained from curFiles[i].name and curFiles[i].size ). The custom returnFileSize() function returns a nicely-formatted version of the size in bytes/KB/MB (by default the browser reports the size in absolute bytes).
  • Generate a thumbnail preview of the image by calling window. URL.createObjectURL (curFiles[i]) and reducing the image size in the CSS, then insert that image into the list item too.
  • If the file type is invalid, we display a message inside a list item telling the user that they need to select a different file type.

The custom validFileType() function takes a File object as a parameter, then loops through the list of allowed file types, checking if any matches the file's type property. If a match is found, the function returns true . If no match is found, it returns false .

The returnFileSize() function takes a number (of bytes, taken from the current file's size property), and turns it into a nicely formatted size in bytes/KB/MB.

The example looks like this — have a play:

Specifications

Browser compatibility.

  • Using files from web applications — contains a number of other useful examples related to <input type="file"> and the File API .

Document Tags and Contributors

  • element represents a clickable button."> <button>
  • element contains a set of <option> elements that represent the values available for other controls."> <datalist>
  • element is used to group several controls as well as labels (<label>) within a web form."> <fieldset>
  • element represents a document section that contains interactive controls to submit information to a web server."> <form>
  • element is used to create interactive controls for web-based forms in order to accept data from the user."> <input>
  • element exists to facilitate generation of key material, and submission of the public key as part of an HTML form. This mechanism is designed for use with Web-based certificate management systems. It is expected that the <keygen> element will be used in an HTML form along with other information needed to construct a certificate request, and that the result of the process will be a signed certificate."> <keygen>
  • element represents a caption for an item in a user interface."> <label>
  • element represents a caption for the content of its parent <fieldset>."> <legend>
  • element represents either a scalar value within a known range or a fractional value."> <meter>
  • element creates a grouping of options within a <select> element."> <optgroup>
  • element is used to define an item contained in a <select>, an <optgroup>, or a <datalist> element. As such, <option> can represent menu items in popups and other lists of items in an HTML document."> <option>
  • element represents the result of a calculation or user action."> <output>
  • element represents the completion progress of a task, typically displayed as a progress bar."> <progress>
  • element represents a control that provides a menu of options:"> <select>
  • element represents a multi-line plain-text editing control."> <textarea>
  • element (or anchor element) creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL."> <a>
  • element represents an abbreviation and optionally provides a full description for it. If present, the title attribute must contain this full description and nothing else."> <abbr>
  • ) allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word. This element has been removed in HTML5. Use <abbr> element."> <acronym>
  • element supplies contact information for its nearest <article> or <body> ancestor; in the latter case, it applies to the whole document."> <address>
  • ) identifies the inclusion of a Java applet."> <applet>
  • element defines a hot-spot region on an image, and optionally associates it with a hypertext link. This element is used only within a <map> element."> <area>
  • element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). Examples include: a forum post, a magazine or newspaper article, or a blog entry."> <article>
  • element represents a section of a document with content connected tangentially to the main content of the document (often presented as a sidebar)."> <aside>
  • element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream."> <audio>
  • element represents a span of text stylistically different from normal text, without conveying any special importance or relevance, and that is typically rendered in boldface."> <b>
  • element specifies the base URL to use for all relative URLs contained within a document. There can be only one <base> element in a document."> <base>
  • ) establishes a default font size for a document. Font size then can be varied relative to the base font size using the <font> element."> <basefont>
  • element (bidirectional isolation) isolates a span of text that might be formatted in a different direction from other text outside it."> <bdi>
  • element (bidirectional override) is used to override the current directionality of text. It causes the directionality of the characters to be ignored in favor of the specified directionality."> <bdo>
  • <bgsound>
  • ) makes the text font size one size bigger (for example, from small to medium, or from large to x-large) up to the browser's maximum font size."> <big>
  • ) is a non-standard element causing the enclosed text to flash slowly."> <blink>
  • Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see Notes for how to change it). A URL for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the <cite> element."> <blockquote>
  • Element represents the content of an HTML document. There can be only one <body> element in a document."> <body>
  • element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant."> <br>
  • element with the canvas scripting API to draw graphics and animations."> <canvas>
  • element represents the title of a table. Though it is always the first descendant of a <table>, its styling, using CSS, may place it elsewhere, relative to the table."> <caption>
  • ) is a block-level element that can contain paragraphs and other block-level and inline elements. The entire content of this element is centered horizontally within its containing element (typically, the <body>)."> <center>
  • element represents a reference to a creative work. It must include the title of a work or a URL reference, which may be in an abbreviated form according to the conventions used for the addition of citation metadata."> <cite>
  • element represents a fragment of computer code. By default, it is displayed in the browser's default monospace font."> <code>
  • element defines a column within a table and is used for defining common semantics on all common cells. It is generally found within a <colgroup> element."> <col>
  • element defines a group of columns within a table."> <colgroup>
  • element—an obsolete part of the Web Components suite of technologies—was used inside of Shadow DOM as an insertion point, and wasn't meant to be used in ordinary HTML It has now been replaced by the <slot> element, which creates a point in the DOM at which a shadow DOM can be inserted."> <content>
  • element links a given content with a machine-readable translation. If the content is time- or date-related, the <time> element must be used."> <data>
  • element indicates the description of a term in a description list (<dl>)."> <dd>
  • element represents a range of text that has been deleted from a document. This element is often (but need not be) rendered with strike-through text."> <del>
  • element is used as a disclosure widget from which the user can retrieve additional information."> <details>
  • element represents the defining instance of a term."> <dfn>
  • element represents a dialog box or other interactive component, such as an inspector or window."> <dialog>
  • ) represents a directory, namely a collection of filenames."> <dir>
  • element is the generic container for flow content and does not inherently represent anything. Use it to group elements for purposes such as styling (using the class or id attributes), marking a section of a document in a different language (using the lang attribute), and so on."> <div>
  •  element represents a description list. The element encloses a list of groups of terms and descriptions. Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs)."> <dl>
  • element identifies a term in a description list. This element can occur only as a child element of a <dl>. It is usually followed by a <dd> element; however, multiple <dt> elements in a row indicate several terms that are all defined by the immediate next <dd> element."> <dt>
  • element marks text that has stress emphasis. The <em> element can be nested, with each level of nesting indicating a greater degree of emphasis."> <em>
  • element represents an integration point for an external application or interactive content (in other words, a plug-in)."> <embed>
  • element represents a caption or a legend associated with a figure or an illustration described by the rest of the data of the <figure> element which is its immediate ancestor."> <figcaption>
  • element represents self-contained content, frequently with a caption (<figcaption>), and is typically referenced as a single unit."> <figure>
  • ) defines the font size, color and face for its content."> <font>
  • element represents a footer for its nearest sectioning content or sectioning root element. A footer typically contains information about the author of the section, copyright data or links to related documents."> <footer>
  • is an HTML element which defines a particular area in which another HTML document can be displayed. A frame should be used within a <frameset>."> <frame>
  • is an HTML element which is used to contain <frame> elements."> <frameset>
  • is the most important and <h6> is the least. A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically."> <h1>
  • is the most important and <h6> is the least. A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically."> <h2>
  • is the most important and <h6> is the least. A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically."> <h3>
  • is the most important and <h6> is the least. A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically."> <h4>
  • is the most important and <h6> is the least. A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically."> <h5>
  • is the most important and <h6> is the least. A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically."> <h6>
  • element provides general information (metadata) about the document, including its title and links to its scripts and style sheets."> <head>
  • element represents a group of introductory or navigational aids. It may contain some heading elements but also other elements like a logo, a search form, and so on."> <header>
  • element represents a multi-level heading for a section of a document. It groups a set of <h1>–<h6> elements."> <hgroup>
  • element represents a thematic break between paragraph-level elements (for example, a change of scene in a story, or a shift of topic with a section). In previous versions of HTML, it represented a horizontal rule. It may still be displayed as a horizontal rule in visual browsers, but is now defined in semantic terms, rather than presentational terms."> <hr>
  • element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element."> <html>
  • element represents a range of text that is set off from the normal text for some reason, for example, technical terms, foreign language phrases, or fictional character thoughts. It is typically displayed in italic type."> <i>
  •  element represents a nested browsing context, effectively embedding another HTML page into the current page. In HTML 4.01, a document may contain a head and a body or a head and a frameset, but not both a body and a frameset. However, an <iframe> can be used within a normal document body. Each browsing context has its own session history and active document. The browsing context that contains the embedded content is called the parent browsing context. The top-level browsing context (which has no parent) is typically the browser window."> <iframe>
  • element represents an image in the document."> <img>
  • element represents a range of text that has been added to a document."> <ins>
  • is an obsolete HTML element that puts a text field in a page for querying the document."> <isindex>
  • element represents user input and produces an inline element displayed in the browser's default monospace font."> <kbd>
  • element is used to represent an item in a list. It must be contained in a parent element: an ordered list (<ol>), an unordered list (<ul>), or a menu (<menu>). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter."> <li>
  • element specifies relationships between the current document and an external resource. Possible uses for this element include defining a relational framework for navigation. This element is most used to link to style sheets."> <link>
  • ) renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML 2 standard recommended that lines shouldn't be broken when not greater than 132 characters."> <listing>
  • element represents the main content of the <body> of a document or application. The main content area consists of content that is directly related to, or expands upon the central topic of, a document or the central functionality of an application."> <main>
  • element is used with <area> elements to define an image map (a clickable link area)."> <map>
  • element represents highlighted text, i.e., a run of text marked for reference purpose, due to its relevance in a particular context."> <mark>
  • element is used to insert a scrolling area of text. You can control what happens when the text reaches the edges of its content area using its attributes."> <marquee>
  • element represents a group of commands that a user can perform or activate. This includes both list menus, which might appear across the top of a screen, as well as context menus, such as those that might appear underneath a button after it has been clicked."> <menu>
  • element represents a command that a user is able to invoke through a popup menu. This includes context menus, as well as menus that might be attached to a menu button."> <menuitem>
  • element represents metadata that cannot be represented by other HTML meta-related elements, like <base>, <link>, <script>, <style> or <title>."> <meta>
  • element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes."> <nav>
  • element prevents a text from breaking into a new line automatically, so it is displayed on one long line and scrolling might be necessary. This tag is not standard HTML and should not be used."> <nobr>
  • is an HTML element which is used to support browsers which are not able to support <frame> elements or configured to do so."> <noframes>
  • element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser."> <noscript>
  • element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin."> <object>
  • element represents an ordered list of items, typically rendered as a numbered list."> <ol>
  • element represents a paragraph of text."> <p>
  • element defines parameters for an <object> element."> <param>
  • element is a container used to specify multiple <source> elements for a specific <img> contained in it. The browser will choose the most suitable source according to the current layout of the page (the constraints of the box the image will appear in) and the device it will be displayed on (e.g. a normal or hiDPI device.)"> <picture>
  • ) renders everything following the start tag as raw text, without interpreting any HTML. There is no closing tag, since everything after it is considered raw text."> <plaintext>
  • element represents preformatted text. Text within this element is typically displayed in a non-proportional ("monospace") font exactly as it is laid out in the file. Whitespace inside this element is displayed as typed.'> <pre>
  • element indicates that the enclosed text is a short inline quotation. This element is intended for short quotations that don't require paragraph breaks; for long quotations use the <blockquote> element."> <q>
  • element is used to provide fall-back parentheses for browsers that do not support display of ruby annotations using the <ruby> element."> <rp>
  • element embraces pronunciation of characters presented in a ruby annotations, which are used to describe the pronunciation of East Asian characters. This element is always used inside a <ruby> element."> <rt>
  • element embraces semantic annotations of characters presented in a ruby of <rb> elements used inside of <ruby> element. <rb> elements can have both pronunciation (<rt>) and semantic (<rtc>) annotations."> <rtc>
  • element represents a ruby annotation. Ruby annotations are for showing pronunciation of East Asian characters."> <ruby>
  • element renders text with a strikethrough, or a line through it. Use the <s> element to represent things that are no longer relevant or no longer accurate. However, <s> is not appropriate when indicating document edits; for that, use the <del> and <ins> elements, as appropriate."> <s>
  • element is an element intended to identify sample output from a computer program. It is usually displayed in the browser's default monotype font (such as Lucida Console)."> <samp>
  • element is used to embed or reference an executable script."> <script>
  • element represents a standalone section of functionality contained within an HTML document, typically with a heading, which doesn't have a more specific semantic element to represent it."> <section>
  • element—an obsolete part of the Web Components technology suite—was intended to be used as a shadow DOM insertion point. You might have used it if you have created multiple shadow roots under a shadow host. It is not useful in ordinary HTML."> <shadow>
  • element—part of the Web Components technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together."> <slot>
  • element makes the text font size one size smaller (for example, from large to medium, or from small to x-small) down to the browser's minimum font size.  In HTML5, this element is repurposed to represent side-comments and small print, including copyright and legal text, independent of its styled presentation."> <small>
  • element specifies multiple media resources for either the <picture>, the <audio> or the <video> element. It is an empty element. It is commonly used to serve the same media content in multiple formats supported by different browsers."> <source>
  • is an obsolete HTML element which allowed insertion of empty spaces on pages. It was devised by Netscape to accomplish the same effect as a single-pixel layout image, which was something web designers used to use to add white spaces to web pages without actually using an image. However, <spacer> no longer supported by any major browser and the same effects can now be achieved using simple CSS. "> <spacer>
  • element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang."> <span>
  • element (or HTML Strikethrough Element) places a strikethrough (horizontal line) over text."> <strike>
  • element gives text strong importance, and is typically displayed in bold."> <strong>
  • element contains style information for a document, or part of a document. By default, the style instructions written inside that element are expected to be CSS."> <style>
  • element defines a span of text that should be displayed, for typographic reasons, lower, and often smaller, than the main span of text."> <sub>
  • element is used as a summary, caption, or legend for the content of a <details> element."> <summary>
  • element defines a span of text that should be displayed, for typographic reasons, higher, and often smaller, than the main span of text."> <sup>
  • element represents tabular data — that is, information expressed via a two-dimensional data table."> <table>
  • element groups one or more <tr> elements as the body of a <table> element."> <tbody>
  • element defines a cell of a table that contains data. It participates in the table model."> <td>
  • element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript."> <template>
  • element defines a set of rows summarizing the columns of the table."> <tfoot>
  • element defines a cell as header of a group of table cells. The exact nature of this group is defined by the scope and headers attributes."> <th>
  • element defines a set of rows defining the head of the columns of the table."> <thead>
  • element represents either a time on a 24-hour clock or a precise date in the Gregorian calendar (with optional time and timezone information)."> <time>
  • element defines the title of the document, shown in a browser's title bar or on the page's tab. It can only contain text, and any contained tags are ignored."> <title>
  • element defines a row of cells in a table. Those can be a mix of <td> and <th> elements."> <tr>
  • element is used as a child of the media elements <audio> and <video>. It lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles. The tracks are formatted in WebVTT format (.vtt files) — Web Video Text Tracks."> <track>
  • ) produces an inline element displayed in the browser's default monotype font. This element was intended to style text as it would display on a fixed width display, such as a teletype. It probably is more common to display fixed width type using the <code> element."> <tt>
  • element renders text with an underline, a line under the baseline of its content. In HTML5, this element represents a span of text with an unarticulated, though explicitly rendered, non-textual annotation, such as labeling the text as being a proper name in Chinese text (a Chinese proper name mark), or labeling the text as being misspelled."> <u>
  • element represents an unordered list of items, typically rendered as a bulleted list."> <ul>
  • element represents a variable in a mathematical expression or a programming context."> <var>
  • element to embed video content in a document."> <video>
  • element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location."> <wbr>
  • ) renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML2 specification recommended that it should be rendered wide enough to allow 80 characters per line."> <xmp>

Header background

Using HTML File Input for Uploading Native iOS/Android Files

post author

October 20, 2020 4 min read

Originally published October 20, 2020

In the last tutorial, we covered how to handle file uploads in Ionic using the <input type="file"> element. This included using the file input element to grab a reference to a file and then upload that file to a Node / Express server (there is also an extension to the tutorial available where we build the backend with NestJS instead).

Those tutorials focused on a desktop/web environment, but what do we do to handle file uploads when our applications are deployed natively to iOS or Android ? Can we still use <input type="file"> ?

The answer to that question is mostly yes , but there are a few things to keep in mind.

Before we get started

What is the difference between web and native for file uploads, differences in file input behaviour between ios and android, standard file input, limiting file input to images, using camera for file input, limiting file input to videos, limiting file input to audio, how do we upload these files to a server.

If you have not already read (or watched) the previous tutorial , it would be a good idea to complete it before reading this one. The previous tutorial provides a lot of important context around how the HTML <input> elements works when specifying the file type, and also around how those files can be uploaded to a backend server with multipart/form-data and the FormData API.

When we use the <input type="file"> element in a standard desktop/web environment, we can be quite certain of its behaviour. We click the Choose file button and a file explorer window is launched where we can select any file on our computer.

When we try to do this on mobile the behaviour is quite different and exactly how it behaves will depend on the platform. Generally speaking, the process is still more or less the same - the user clicks the button, selects a file, and then we are able to get a reference to that file. However, we don't have a standard "file explorer" window that pops up and allows the user to select any file on their device. Depending on the context, the camera might be launched directly, or the user might be prompted to choose a file directly from the file system, or the user might be offered a choice between browsing files, taking a photo, taking a video, and so on.

Let's take a look at different ways to set up the file input.

Although the following is not an exhaustive list of ways to set up the file input element, these are a pretty good set of examples that we could default to.

NOTE: The examples below use Angular event bindings to handle the change event, but otherwise the implementation will be the same with vanilla JavaScript , StencilJS , React , Vue , or whatever else you are using.

On iOS , this will prompt the user to choose between Take Photo or Video , Photo Library , or Browse in order to return the desired file.

On Android , this will directly launch the native file selection screen to select any file on the device.

Opening file input element on ios and android

On iOS , this will prompt the user to choose between Take Photo , Photo Library , or Browse in order to return the desired file. Note that Video is no longer a choice in the first option and videos (and other files) will also be excluded from being listed if the user chooses to select an existing photo.

On Android , this will launch the same native file selection screen again, but this time it will be filtered to only show images.

Opening file input element limited to images on ios and android

On iOS , this will directly launch the camera in Photo mode and allow the user to take a photo. Once the user takes a photo they will be able to choose whether to use that photo or if they want to retake the photo. Once the user chooses Use Photo the file will be supplied to the application.

On Android , this will directly launch the camera allowing the user to take a photo (not a video). The user can then accept the taken photo or take another.

Opening file input element with camera on ios and android

On iOS , this will prompt the user to choose between Take Video , Photo Library , or Browse in order to return the desired file. Note that Photo is no longer a choice in the first option and photos (and other files) will also be excluded from being listed if the user chooses to select an existing video.

On Android , this will launch the native file selection screen again, but this time it will be filtered to only show videos.

Opening file input element limited to video on ios and android

On iOS , this will prompt the user to choose between Take Photo or Video , Photo Library , or Browse in order to return the desired file. Note that there is no restriction to audio files only in this case.

On Android , this will launch the native file selection screen again, but this time it will be filtered to only show audio files.

Opening file input element limited to audio on ios and android

Keep in mind that the specification for the file input element has changed over the years, so you might find many different examples of ways to set up this element and force certain behaviours. In general, my advice would be not to try to "game the system". Use the simplest options and focus on telling the browser what you want, then let the platform decide how best to fulfill that request. If you try to get too tricky and take over this process to enforce what you want, you will leave yourself vulnerable to different behaviours on different platforms/versions and also your solution will be more prone to breaking in the future.

If you do need more control over this process, in ways that using the file input element does not allow (or at least it does not allow it consistently across platforms), you can look into using native plugins/APIs instead. The Camera API , for example, will give you much greater control over the process of selecting/capturing a photo than the <input type="file"> element will.

Fortunately, the resulting file reference can be uploaded in the same way as a file retrieved from a normal desktop/web file input element. You will just need to make a POST request that includes multipart/form-data that contains the file(s) you want to upload. For more details on doing that, check out the previous tutorial: Handling File Uploads in Ionic .

The standard <input type="file"> element provides a surprisingly smooth file selection experience on native iOS and Android platforms, and these files can be easily sent as standard multipart/form-data to your backend server. This will probably be all you need a lot of the time, but for certain specialised circumstances or use cases you might need to look into using native plugins or APIs to fulfil your file selection and transferring needs.

If you enjoyed this article, feel free to share it with others!

accept attribute for file input

Allows a filter to be defined for what type of files a user may pick with from an &lt;input type="file"> dialog

  • 4 : Not supported
  • 5 - 8 : Support unknown
  • 9 - 20 : Partial support
  • 21 - 25 : Support unknown
  • 26 - 123 : Supported
  • 124 : Supported
  • 125 - 127 : Supported
  • 12 - 18 : Not supported
  • 79 - 122 : Supported
  • 123 : Supported
  • 3.1 - 5.1 : Not supported
  • 6 - 11 : Partial support
  • 11.1 - 17.3 : Supported
  • 17.4 : Supported
  • 17.5 - TP : Supported
  • 2 - 3.6 : Not supported
  • 4 - 36 : Partial support
  • 37 - 124 : Supported
  • 125 : Supported
  • 126 - 128 : Supported
  • 9 - 12.1 : Not supported
  • 15 - 108 : Supported
  • 109 : Supported
  • 5.5 - 9 : Not supported
  • 10 : Supported
  • 11 : Supported

Chrome for Android

  • 123 : Partial support

Safari on iOS

  • 3.2 - 5.1 : Not supported
  • 6 - 7.1 : Not supported
  • 8 - 17.3 : Partial support
  • 17.4 : Partial support
  • 17.5 : Partial support

Samsung Internet

  • 4 - 23 : Partial support
  • 24 : Partial support
  • all : Not supported

Opera Mobile

  • 10 - 12.1 : Not supported
  • 80 : Not supported

UC Browser for Android

  • 15.5 : Not supported

Android Browser

  • 2.1 - 2.3 : Not supported
  • 3 - 4.3 : Partial support
  • 4.4 - 4.4.4 : Not supported
  • 123 : Not supported

Firefox for Android

  • 124 : Not supported
  • 14.9 : Partial support

Baidu Browser

  • 13.52 : Partial support

KaiOS Browser

  • 2.5 : Supported
  • 3 : Supported

Not supported means any file can be picked as if the accept attribute was not set, unless otherwise noted.

On Windows, files that do not apply are hidden. On OSX they are grayed out and disabled.

Input File don`t work on IOS

I am trying use upload images from my phone to my website across tag html5 input file my command is <input type="file" id="file2" name="file2" accept="image/*;capture=camera" >

I trying other parameters too how *.jpg, .jpeg and more.

All others browsers works fine, include the safari on my macbook, but the safari mobile don`t work.

I connect the my phone on safari log developer but don`t work any message of error.

When I press button upload i can choose gallery or camera, I select the file but don`t do upload to my website.

What the problem? How I solve?

I tested on Iphone 7, XS, emulator 12 with IOS 14.3

  • Safari Developer Tools
  • Safari and Web

It's embarassing. Still not working for me.

Site Logo

Nikita Hlopov

Frontend Dev Blog

Custom styled input type file upload button with pure CSS

In this guide I’ll show you how to create a stylish and user friendly file upload button with pure CSS and HTML.

To upload files you’ll need to use the input tag with type="file" attribute. Additionally you can specify which file types you’re allowing to upload via accept attribute.

This markup produces a button with a Choose file title followed by a text which indicates the file name when selected. By default it is No file chosen .

Input with type file default look differs on different browsers:

Input type file on Chrome

The upload file widget structure consists of a block that displays a button and a file name. A user can click anywhere inside the block or drag a file from the desktop and it will open up the upload window.

Styling the upload file block

If you apply styles for the input[type=file] selector it will set them for the whole widget block, that is the button and text.

The result already looks much better as it indicates the zone where user is able to click or drag the file.

Styling the upload file button

By default, the Choose file button has a plain user-agent style. To style the button with CSS you should use the ::file-selector-button pseudo-element to select it. It is supported in all modern browsers .

Styling the the click/drop zone

If you wich to go a bit further, you can create a large zone where user can click and drag files. This large zone will make it easier for people to use the widget, as it don’t require to be that precise when dragging a file, especially on smaller screens.

To implement a large drop zone, you’ll need to wrap your file upload input into a label tag and specify a description text that will let users know how to use the widget.

For the layout, we need to set display to flex with flex related properties for positioning. The height and padding properties for proportion. And finally add some fancy styles like border and hover effects to highlight the file upload zone and you’re ready to go.

Drop files here or

Handling drag and drop events

Additionally, you can handle cases when the user will try to drag the file over the drop area. CSS alone cannot handle such cases, so we can add a little bit of JavaScript.

There are two points to consider to improve UX for the drop field:

  • Indicate the drop area when the user is dragging a file over it
  • Make it possible to drop a file inside the drop area, and not just the input element

To indicate drop area when user is dragging a file over it, we’ll need to use the dragenter and dragleave events . Both on the label tag, since it represents the drop area. For each event we add or remove a CSS class accordingly.

Since user will be dropping to the label tag we also need to set the input value with the file. To do that we need to do 2 things:

  • Set dragover event for the label tag, set e.preventDefault() and pass false as the third parameter for the addEventListener method
  • On drop event, we need to set the input’s files property to the file via fileInput.files = e.dataTransfer.files

As for styles, we can use similar styles to :hover state, but this time with a designated class:

See the full example on CodePen:

See the Pen Untitled by Nikita Hlopov ( @nikitahl ) on CodePen .

Shortcuts User Guide

  • Intro to Shortcuts
  • Discover shortcuts in the Gallery
  • Run a shortcut from the app
  • Run shortcuts with Siri
  • Run suggested shortcuts
  • Run app shortcuts
  • Run shortcuts from the Home Screen widget
  • Run shortcuts from the Search screen
  • Add a shortcut to the Home Screen
  • Launch a shortcut from another app
  • Run shortcuts from Apple Watch
  • Run shortcuts by tapping the back of your iPhone
  • Adjust privacy settings
  • Intro to how shortcuts work
  • The flow of content
  • Action connections
  • Control the flow of actions
  • Shortcut completion
  • The Content Graph engine
  • Create a custom shortcut
  • Ideas for custom shortcuts
  • Navigate the action list
  • Order of actions
  • Get actions
  • Transform actions
  • Share actions
  • Test your actions
  • About actions in complicated shortcuts
  • Intro to editing shortcuts
  • Organize shortcuts in folders
  • Change the layout
  • Reorder shortcuts
  • Rename shortcuts
  • Modify shortcut icons
  • Duplicate shortcuts
  • Delete shortcuts
  • Sync shortcuts
  • Share shortcuts
  • Add import questions to shared shortcuts
  • Add a shortcut to Reminders using Siri
  • Intro to personal automation
  • Create a new personal automation
  • Enable or disable a personal automation
  • Delete a personal automation
  • Event triggers
  • Travel triggers
  • Communication triggers
  • Transaction trigger
  • Setting triggers
  • Intro to home automation
  • Create a new home automation
  • Enable or disable a home automation
  • Delete a home automation
  • Home automation triggers
  • Intro to variables
  • Variable types
  • Use variables
  • Adjust variables
  • Use list actions
  • Use the Choose from Menu action
  • Use If actions
  • Use Repeat actions
  • Intro to Find and Filter actions
  • Add filter parameters
  • Intro to using prompts
  • Use the Ask for Input action
  • Use the Ask Each Time variable
  • Use the Show Alert action
  • Use the Show Notification action
  • Input types
  • Limit the input for a shortcut
  • Receive onscreen items
  • Advanced Shortcuts settings
  • Intro to the Run JavaScript on Webpage action
  • Use the Run JavaScript on Webpage action
  • Intro to URL schemes
  • Open, create, and run a shortcut
  • Run a shortcut from a URL
  • Open or search the Gallery from a URL
  • Use x-callback-url
  • Use another app’s URL scheme
  • Intro to web APIs
  • What’s an API?
  • Request your first API
  • Intro to using JSON
  • Parsing JSON
  • Handling lists
  • Get Dictionary Value action
  • Create contacts
  • API limitations
  • Format Date timestamps
  • Dictionaries
  • About date and time formatting
  • Date and time formats
  • Dates as written language
  • Technical standards
  • Custom date formats

input type file safari

Understanding input types in Shortcuts on iPhone or iPad

If you’ve set your shortcut to launch from another app , you can open the shortcut from other apps. When run from other apps, the shortcut receives input—such as a URL or an image—from the app. The input from the host app is passed into the first action of your shortcut.

You can specify which input types the shortcut can accept. The default input type is Any, which allows the shortcut to appear in any app.

When you change input types, the shortcut appears only in apps that share the specified type of content. For example, a shortcut that accepts only URLs appears when you run the shortcut from Safari, but does not appear when you run the shortcut from Photos. Shortcuts that don’t work with the current app are hidden.

Tip: Specify an input type for each of your shortcuts so that your share sheet is organized when opened.

Note: At times, shortcuts may appear in unexpected places—for example, a shortcut that accepts images appears when sharing a webpage in Safari (because webpages can contain images).

The following table lists supported input types.

Tip: To explore what an app passes into Shortcuts, set up a shortcut that accepts Anything and includes only a View Content Graph action. When the shortcut is run from the the app, the content items that the Content Graph can identify are displayed.

HTML References

Html <input type="file">.

❮ HTML <input> type attribute

Define a file-select field:

Definition and Usage

The <input type="file"> defines a file-select field and a "Browse" button for file uploads.

To define a file-select field that allows multiple files to be selected, add the multiple attribute.

Tip: Always add the <label> tag for best accessibility practices!

Browser Support

The numbers in the table specify the first browser version that fully supports the element.

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

WebKit Features in Safari 16.4

Mar 27, 2023

by Patrick Angle, Marcos Caceres, Razvan Caliman, Jon Davis, Brady Eidson, Timothy Hatcher, Ryosuke Niwa, and Jen Simmons

Web Push on iOS and iPadOS

Improvements for web apps, web components, javascript and webassembly, images, video, and audio, developer tooling, web inspector, safari web extensions, safari content blockers, new restrictions in lockdown mode, more improvements.

Today, we’re thrilled to tell you about the many additions to WebKit that are included in Safari 16.4. This release is packed with 135 new web features and over 280 polish updates. Let’s take a look.

You can experience Safari 16.4 on macOS Ventura , macOS Monterey, macOS Big Sur, iPadOS 16 , and iOS 16 . Update to Safari 16.4 on macOS Monterey or macOS Big Sur by going to System Preferences → Software Update → More info, and choosing to update Safari. Or update on macOS Ventura, iOS or iPadOS, by going to Settings → General → Software Update.

input type file safari

iOS and iPadOS 16.4 add support for Web Push to web apps added to the Home Screen. Web Push makes it possible for web developers to send push notifications to their users through the use of Push API , Notifications API , and Service Workers .

Deeply integrated with iOS and iPadOS, Web Push notifications from web apps work exactly like notifications from other apps. They show on the Lock Screen, in Notification Center, and on a paired Apple Watch. Focus provides ways for users to precisely configure when or where to receive Web Push notifications — putting users firmly in control of the experience. For more details, read Web Push for Web Apps on iOS and iPadOS .

WebKit on iOS and iPadOS 16.4 adds support for the Badging API . It allows web app developers to display an app badge count just like any other app on iOS or iPadOS. Permission for a Home Screen web app to use the Badging API is automatically granted when a user gives permission for notifications.

To support notifications and badging for multiple installs of the same web app, WebKit adds support for the id member of the Web Application Manifest standard. Doing so continues to provide users the convenience of saving multiple copies of a web app, perhaps logged in to different accounts separating work and personal usage — which is especially powerful when combined with the ability to customize Home Screen pages with different sets of apps for each Focus .

iOS and iPadOS 16.4 also add support so that third-party web browsers can offer “Add to Home Screen” in the Share menu. For the details on how browsers can implement support, as well more information about all the improvements to web apps, read Web Push for Web Apps on iOS and iPadOS .

We continue to care deeply about both the needs of a wide-range of web developers and the everyday experience of users. Please keep sending us your ideas and requests . There’s more work to do, and we couldn’t be more excited about where this space is headed.

Web Components is a suite of technologies that together make it possible to create reusable custom HTML elements with encapsulated functionality. Safari 16.4 improves support for Web Components with several powerful new capabilities.

Safari 16.4 adds support Declarative Shadow DOM, allowing developers to define shadow DOM without the use of JavaScript. And it adds support for ElementInternals , providing the basis for improved accessibility for web components, while enabling custom elements to participate in forms alongside built-in form elements.

Also, there’s now support for the Imperative Slot API. Slots define where content goes in the template of a custom element. The Imperative Slot API allows developers to specify the assigned node for a slot element in JavaScript for additional flexibility.

Safari 16.4 adds support for quite a few new CSS properties, values, pseudo-classes and syntaxes. We are proud to be leading the way in several areas to the future of graphic design on the web.

Margin Trim

The margin-trim property can be used to eliminate margins from elements that are abutting their container. For example, imagine we have a section element, and inside it we have content consisting of an h2 headline and several paragraphs. The section is styled as a card, with an off-white background and some padding. Like usual, the headline and paragraphs all have top and bottom margins — which provide space between them. But we actually don’t want a margin above the first headline, or after the last paragraph. Those margins get added to the padding, and create more space than what’s desired.

input type file safari

Often web developers handle this situation by removing the top margin on the headline with h2 { margin-block-start: 0 } and the bottom margin on the last paragraph with p:last-child { margin-block-end: 0 } — and hoping for the best. Problems occur, however, when unexpected content is placed in this box. Maybe another instance starts with an h3 , and no one wrote code to remove the top margin from that h3 . Or a second h2 is written into the text in the middle of the box, and now it’s missing the top margin that it needs.

The margin-trim property allows us to write more robust and flexible code. We can avoid removing margins from individual children, and instead put margin-trim: block on the container.

input type file safari

This communicates to the browser: please trim away any margins that butt up against the container. The rule margin-trim: block trims margins in the block direction, while margin-trim: inline trims margins in the inline direction.

Try this demo for yourself in Safari 16.4 or Safari Technology Preview to see the results.

Safari 16.4 also adds support for the new line height and root line height units, lh and rlh . Now you can set any measurement relative to the line-height. For example, perhaps you’d like to set the margin above and below your paragraphs to match your line-height.

The lh unit references the current line-height of an element, while the rlh unit references the root line height — much like em and rem.

Safari 16.4 adds support for font-size-adjust . This CSS property provides a way to preserve the apparent size and readability of text when different fonts are being used. While a web developer can tell the browser to typeset text using a specific font size, the reality is that different fonts will render as different visual sizes. You can especially see this difference when more than one font is used in a single paragraph. In the following demo , the body text is set with a serif font, while the code is typeset in a monospace font — and they do not look to be the same size. The resulting differences in x-height can be quite disruptive to reading. The demo also provides a range of font fallback options for different operating systems, which introduces even more complexity. Sometimes the monospace font is bigger than the body text, and other times it’s smaller, depending on which font family is actually used. The font-size-adjust property gives web developers a solution to this problem. In this case, we simply write code { font-size-adjust: 0.47; } to ask the browser to adjust the size of the code font to match the actual glyph size of the body font.

input type file safari

To round out support for the font size keywords, font-size: xxx-large is now supported in Safari 16.4.

Pseudo-classes

Safari 16.4 also adds support for several new pseudo-classes. Targeting a particular text direction, the :dir() pseudo-class lets you define styles depending on whether the language’s script flows ltr (left-to-right) or rtl ( right-to-left ). For example, perhaps you want to rotate a logo image a bit to the left or right, depending on the text direction:

Along with unprefixing the Fullscreen API (see below), the CSS :fullscreen pseudo-class is also now unprefixed. And in Safari 16.4, the :modal pseudo-class also matches fullscreen elements.

Safari 16.4 adds :has() support for the :lang pseudo-class, making it possible to style any part of a page when a particular language is being used on that page. In addition, the following media pseudo-classes now work dynamically inside of :has() , opening up a world of possibilities for styling when audio and video are in different states of being played or manipulated — :playing , :paused , :seeking , :buffering , :stalled , :picture-in-picture , :volume-locked , and :muted . To learn more about :has() , read Using :has() as a CSS Parent Selector and much more .

Safari 16.4 adds support for Relative Color Syntax. It provides a way to specify a color value in a much more dynamic fashion. Perhaps you want to use a hexadecimal value for blue, but make that color translucent — passing it into the hsl color space to do the calculation.

Or maybe you want to define a color as a variable, and then adjust that color using a mathematical formula in the lch color space, telling it to cut the lightness ( l ) in half with calc(l / 2) , while keeping the chroma ( c ) and hue ( h ) the same.

Relative Color Syntax is powerful. Originally appearing in Safari Technology Preview 122 in Feb 2021, we’ve been waiting for the CSS Working Group to complete its work so we could ship. There isn’t documentation on MDN or Can I Use about Relative Color Syntax yet, but likely will be soon. Meanwhile the Color 5 specification is the place to learn all about it.

Last December, Safari 16.2 added support for color-mix() . Another new way to specify a color value, the functional notation of color-mix makes it possible to tell a browser to mix two different colors together, using a certain color space .

Safari 16.4 adds support for using currentColor with color-mix() . For example, let’s say we want to grab whatever the current text color might be, and mix 50% of it with white to use as a hover color. And we want the mathematical calculations of the mixing to happen in the oklab color space. We can do exactly that with:

Safari 16.2 also added support for Gradient Interpolation Color Spaces last December. It allows the interpolation math of gradients — the method of determining intermediate color values — to happen across different color spaces. This illustration shows the differences between the default sRGB interpolation compared to interpolation in lab and lch color spaces:

input type file safari

Safari 16.4 adds support for the new system color keywords . Think of them as variables which represent the default colors established by the user, browser, or OS — defaults that change depending on whether the system is set to light mode, dark mode, high contrast mode, etc. For instance, Canvas represents the current default background color of the HTML page. Use system color keywords just like other named colors in CSS. For example, h4 { color: FieldText; } will style h4 headlines to match the default color of text inside form fields. When a user switches from light to dark mode, the h4 color will automatically change as well. Find the full list of system colors in CSS Color level 4 .

Media Queries Syntax Improvements

Safari 16.4 adds support for the syntax improvements from Media Queries level 4. Range syntax provides an alternative way to write out a range of values for width or height. For example, if you want to define styles that are applied when the browser viewport is between 400 and 900 pixels wide, in the original Media Query syntax, you would have written:

Now with the new syntax from Media Queries level 4, you can instead write:

This is the same range syntax that’s been part of Container Queries from its beginning, which shipped in Safari 16.0 .

Media Queries level 4 also brings more understandable syntax for combining queries using boolean logic with and , not , and or . For example:

Can instead be greatly simplified as:

Or, along with the range syntax changes, as:

Custom Properties

Safari 16.4 adds support for CSS Properties and Values API with support for the @property at-rule. It greatly extends the capabilities of CSS variables by allowing developers to specify the syntax of the variable, the inheritance behavior, and the variable initial value — similar to how browser engines define CSS properties.

With @property support, developers can to do things in CSS that were impossible before, like animate gradients or specific parts of transforms.

Web Animations

Safari 16.4 includes some additional improvements for web animations. You can animate custom properties. Animating the blending of mismatched filter lists is now supported. And Safari now supports KeyframeEffect.iterationComposite .

Outline + Border Radius

Until now, if a web developer styled an element that had an outline with a custom outline-style , and that element had curved corners, the outline would not follow the curve in Safari. Now in Safari 16.4, outline always follows the curve of border-radius .

CSS Typed OM

Safari 16.4 adds support for CSS Typed OM , which can be used to expose CSS values as typed JavaScript objects. Input validation for CSSColorValues is also supported as part of CSS Typed OM. Support for Constructible and Adoptable CSSStyleSheet objects also comes to Safari 16.4.

Safari 16.4 now supports lazy loading iframes with loading="lazy" . You might put it on a video embed iframe, for example , to let the browser know if this element is offscreen, it doesn’t need to load until the user is about to scroll it into view.

By the way, you should always include the height and width attributes on iframes, so browsers can reserve space in the layout for it before the iframe has loaded. If you resize the iframe with CSS, be sure to define both width and height in your CSS. You can also use the aspect-ratio property to make sure an iframe keeps it’s shape as it’s resized by CSS.

Now in Safari 16.4, a gray line no longer appears to mark the space where a lazy-loaded image will appear once it’s been loaded.

Safari 16.4 also includes two improvements for <input type="file"> . Now a thumbnail of a selected file will appear on macOS. And the cancel event is supported.

Safari 16.4 brings a number of useful new additions for developers in JavaScript and WebAssembly.

RegExp Lookbehind makes it possible to write Regular Expressions that check what’s before your regexp match. For example, match patterns like (?<=foo)bar matches bar only when there is a foo before it. It works for both positive and negative lookbehind.

JavaScript Import Maps give web developers the same sort of versioned file mapping used in other module systems, without the need for a build step.

Growable SharedArrayBuffer provided a more efficient mechanism for growing an existing buffer for generic raw binary data. And resizable ArrayBuffer allows for resizing of a byte array in JavaScript.

In WebAssembly, we’ve added support for 128-bit SIMD.

Safari 16.4 also includes:

  • Array.fromAsync
  • Array#group and Array#groupToMap
  • Atomics.waitAsync
  • import.meta.resolve()
  • Intl.DurationFormat
  • String#isWellFormed and String#toWellFormed
  • class static initialization blocks
  • Symbols in WeakMap and WeakSet

Safari 16.4 adds support for quite a few new Web API. We prioritized the features you’ve told us you need most.

Offscreen Canvas

When using Canvas, the rendering, animation, and user interaction usually happens on the main execution thread of a web application. Offscreen Canvas provides a canvas that can be rendered off screen, decoupling the DOM and the Canvas API so that the <canvas> element is no longer entirely dependent on the DOM. Rendering can now also be transferred to a worker context, allowing developers to run tasks in a separate thread and avoid heavy work on the main thread that can negatively impact the user experience. The combination of DOM-independent operations and rendering of the main thread can provide a significantly better experience for users, especially on low-power devices. In Safari 16.4 we’ve added Offscreen Canvas support for 2D operations. Support for 3D in Offscreen Canvas is in development.

Fullscreen API

Safari 16.4 now supports the updated and unprefixed Fullscreen API on macOS and iPadOS. Fullscreen API provides a way to present a DOM element’s content so that it fills the user’s entire screen, and to exit fullscreen mode once it’s unneeded. The user is given control over exiting fullscreen mode through various mechanisms, include pressing the ‘Esc’ key on the keyboard, or performing a downwards gesture on touch-enabled devices. This ensures that the user always has the ability to exit fullscreen whenever they desire, preserving their control over the browsing experience.

Screen Orientation API

Along with the Fullscreen API we’ve added preliminary support for Screen Orientation API in Safari 16.4, including:

  • ScreenOrientation.prototype.type returns the screen’s current orientation.
  • ScreenOrientation.prototype.angle returns the screen’s current orientation angle.
  • ScreenOrientation.prototype.onchange event handler, which fires whenever the screen changes orientation.

Support for the lock() and unlock() methods remain experimental features for the time being. If you’d like to try them out, you can enable them in the Settings app on iOS and iPadOS 16.4 via Safari → Advanced → Experimental Features → Screen Orientation API (Locking / Unlocking).

Screen Wake Lock API

The Screen Wake Lock API provides a mechanism to prevent devices from dimming or locking the screen. The API is useful for any application that requires the screen to stay on for an extended period of time to provide uninterrupted user experience, such as a cooking site, or for displaying a QR code.

User Activation API

User Activation API provides web developers with a means to check whether a user meaningfully interacted with a web page. This is useful as some APIs require meaningful “user activation”, such as, a click or touch, before they can be used. Because user activation is based on a timer, the API can be used to check if document currently has user activation as otherwise a call to an API would fail. Read The User Activation API for more details and usage examples.

WebGL Canvas Wide Gamut Color

WebGL canvas now supports the display-p3 wide-gamut color space. To learn more about color space support, read Improving Color on the Web , Wide Gamut Color in CSS with Display-P3 , and Wide Gamut 2D Graphics using HTML Canvas .

Compression Streams API

Compression Streams API allows for compressing and decompressing streams of data in directly in the browser, reducing the need for a third-party JavaScript compression library. This is handy if you need to “gzip” a stream of data to send to a server or to save on the user’s device.

Safari 16.4 also includes many other new Web API features, including:

  • Reporting API
  • Notification API in dedicated workers
  • Permissions API for dedicated workers
  • Service Workers and Shared Workers to the Permissions API
  • gamepad.vibrationActuator
  • A submitter parameter in the FormData constructor
  • COEP violation reporting
  • COOP/COEP navigation violation reporting
  • Fetch Initiator
  • Fetch Metadata Request Headers
  • importing compressed EC keys in WebCrypto
  • loading scripts for nested workers
  • non-autofill credential type for the autocomplete attribute
  • revoking Blob URLs across same-origin contexts
  • isComposing attribute on InputEvent
  • termination of nested workers
  • transfer size metrics for first parties in ServerTiming and PerformanceResourceTiming
  • KeyframeEffect.iterationComposite
  • WEBGL_clip_cull_distance

Last fall, Safari 16 brought support for AVIF images to iOS 16, iPadOS 16 and macOS Ventura. Now with Safari 16.4, AVIF is also supported on macOS Monterey and macOS Big Sur. Updates to our AVIF implementation ensure animated images and images with film grain (noise synthesis) are now fully supported, and that AVIF works inside the <picture> element. We’ve also updated our AVIF implementation to be more lenient in accepting and displaying images that don’t properly conform to the AVIF standard.

Safari 16.4 adds support for the video portion of Web Codecs API . This gives web developers complete control over how media is processed by providing low-level access to the individual frames of a video stream. It’s especially useful for applications that do video editing, video conferencing, or other real-time processing of video.

Media features new to Safari 16.4 also include:

  • Improvements to audio quality for web video conferencing
  • Support for a subset of the AudioSession Web API
  • Support for AVCapture virtual cameras
  • Support for inbound rtp trackIdentifier stat field
  • Support for VTT-based extended audio descriptions
  • Support to allow a site to provide an “alternate” URL to be used during AirPlay

WKPreferences , used by WKWebView on iOS and iPadOS 16.4, adds a new shouldPrintBackgrounds API that allows clients to opt-in to including a pages’s background when printing.

Inspectable WebKit and JavaScriptCore API

Across all platforms supporting WKWebView or JSContext , a new property is available called isInspectable ( inspectable in Objective-C) on macOS 13.4 and iOS, iPadOS, and tvOS 16.4. It defaults to false , and you can set it to true to opt-in to content being inspectable using Web Inspector, even in release builds of apps.

Develop Menu > Patrick's iPhone > Example App

When an app has enabled inspection, it can be inspected from Safari’s Develop menu in the submenu for either the current computer or an attached device. For iOS and iPadOS, you must also have enabled Web Inspector in the Settings app under Safari > Advanced > Web Inspector .

To learn more, read Enabling the Inspection of Web Content in Apps .

When automating Safari 16.4 with safaridriver , we now supports commands for getting elements inside shadow roots, as well as accessibility commands for getting the computed role and label of elements. When adding a cookie with safaridriver , the SameSite attribute is now supported. Improvements have also been made to performing keyboard actions, including better support for modifier keys behind held and support for typing characters represented by multiple code points, including emoji. These improvements make writing cross-browser tests for your website even easier.

Typography Tooling

Web Inspector in Safari 16.4 adds new typography inspection capabilities in the Fonts details sidebar of the Elements Tab.

input type file safari

Warnings are now shown for synthesized bold and oblique when the rendering engine has to generate these styles for a font that doesn’t provide a suitable style. This may be an indicator that the font file for a declared @font-face was not loaded. Or it may be that the specific value for font-weight or font-style isn’t supported by the used font.

A variable font is a font format that contains instructions on how to generate, from a single file, multiple style variations, such as weight, stretch, slant, optical sizing, and others. Some variable fonts allow for a lot of fine-tuning of their appearance, like the stroke thickness, the ascender height or descender depth, and even the curves or roundness of particular glyphs. These characteristics are expressed as variation axes and they each have a custom value range defined by the type designer.

input type file safari

The Fonts details sidebar now provides interactive controls to adjust values of variation axes exposed by a variable font and see the results live on the inspected page allowing you to get the font style that’s exactly right for you.

Tooling for Conditionals in CSS

The controls under the new User Preference Overrides popover in the Elements Tab allow you to emulate the states of media features like prefers-reduced-motion and prefers-contrast to ensure that the web content you create adapts to the user’s needs. The toggle to emulate the states of prefers-color-scheme , which was previously a standalone button, has moved to this new popover.

input type file safari

The Styles panel of the Elements Tab now allows editing the condition text for @media , @container and @supports CSS rules. This allows you to make adjustments in-context and immediately see the results on the inspected page. Here’s a quick tip: edit the condition of @supports to its inverse, like @supports not (display: grid) , to quickly check your progressive enhancement approach to styling and layout.

Badging HTML Elements

input type file safari

New badges for elements in the DOM tree of the Elements Tab join the existing badges for Grid and Flex containers. The new Scroll badge calls out scrollable elements, and the new Events badge provides quick access to the event listeners associated with the element when clicked. And a new Badges toolbar item makes it easy to show just the badges you are interested in and hide others.

Changes to Web Inspector in Safari 16.4 also include:

  • Elements Tab: Improved visual hierarchy of the Layout sidebar.
  • Elements Tab: Added support for nodes that aren’t visible on the page to appear dimmed in the DOM tree.
  • Console Tab: Added support for console snippets.
  • Sources Tab: Added showing relevant special breakpoints in the Pause Reason section.
  • Sources Tab: Added support for inline breakpoints.
  • Sources Tab: Added support for symbolic breakpoints
  • Network Tab: Added a Path column.
  • Network Tab: Added alphabetic sorting of headers.
  • Network Tab: Added support for per-page network throttling.
  • Network Tab: Added using the Shift key to highlight the initiator or initiated resources.
  • Graphics Tab: Added OpenGL object IDs in the Canvas inspector.
  • Settings Tab: Added a setting to turn off dimming nodes that aren’t visible on the page.
  • Added support for function breakpoints and tracepoints.

Enhancements to Declarative Net Request

Safari is always working on improving support for declarativeNetRequest , the declarative way for web extensions to block and modify network requests. In Safari 16.4, several enhancements have been added to the API:

  • The declarativeNetRequest.setExtensionActionOptions API can be used to configure whether to automatically display the action count (number of blocked loads, etc.) as the extension’s badge text.
  • The modifyHeaders action type has been added to rewrite request and response headers. This action requires granted website permissions for the affected domains and the declarativeNetRequestWithHostAccess permission in the manifest.
  • The redirect action type now requires the declarativeNetRequestWithHostAccess permission in the manifest.
  • The MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES property has been added to check the maximum number of combined dynamic and session rules an extension can add. The current limit is set at 5,000 rules.

These enhancements give developers more options to customize their content blocking extensions and provide users with better privacy protection.

SVG Icon Support in Web Extensions

Safari 16.4 now supports SVG images as extension and action icons, giving developers more options for creating high-quality extensions. This support brings Safari in line with Firefox, allowing for consistent experiences across platforms. The ability to scale vector icons appropriately for any device means developers no longer need multiple sizes, simplifying the process of creating polished and professional-looking extensions.

Dynamic Content Scripts

Safari 16.4 introduces support for the new scripting.registerContentScript API, which enables developers to create dynamic content scripts that can be registered, updated, or removed programmatically. This API augments the static content scripts declared in the extension manifest, providing developers with more flexibility in managing content scripts and enabling them to create more advanced features for their extensions.

Toggle Reader Mode

The tabs.toggleReaderMode API has been added to Safari 16.4, which enables extensions to toggle Reader Mode for any tab. This function is particularly useful for extensions that want to enhance the user’s browsing experience by allowing them to focus on the content they want to read. By using this API, developers can create extensions that automate the process of enabling Reader Mode for articles, making it easier and more convenient for users to read online content.

Session Storage

The storage.session API, now supported in Safari 16.4, enables extensions to store data in memory for the duration of the browser session, making it a useful tool for storing data that takes a long time to compute or is needed quickly between non-persistent background page loads. This API is particularly useful for storing sensitive or security-related data, such as decryption keys or authentication tokens, that would be inappropriate to store in local storage. The session storage area is not persisted to disk and is cleared when Safari quits, providing enhanced security and privacy for users.

Background Modules

Developers can now take advantage of modules in background service workers and pages by setting "type": "module" in the background section of the manifest. This allows for more organized and maintainable extension code, making it easier to manage complex codebases. By setting this option, background scripts will be loaded as ES modules, enabling the use of import statements to load dependencies and use the latest JavaScript language features.

Safari 16.4 has added support for :has() selectors in Safari Content Blocker rules. This is a powerful new addition to the declarative content blocking capabilities of Safari, as it allows developers to select and hide parent elements that contain certain child elements. Its inclusion in Safari Content Blocker rules opens up a whole new range of possibilities for content blocking. Now developers can create more nuanced and precise rules that can target specific parts of a web page, making it easier to block unwanted content while preserving the user’s browsing experience. This is yet another example of Safari’s commitment to providing a secure and private browsing experience for its users while also offering developers the tools they need to create innovative and effective extensions.

Lockdown Mode is an optional, extreme protection that’s designed for the very few individuals who, because of who they are or what they do, might be personally targeted by some of the most sophisticated digital threats. Most people are never targeted by attacks of this nature.

If a user chooses to enable Lockdown mode on iOS 16.4, iPadOS 16.4, or macOS Ventura 13.3, Safari will now:

  • Disable binary fonts in the CSS Font Loading API
  • Disable Cache API
  • Disable CacheStorage API
  • Disable ServiceWorkers
  • Disable SVG fonts
  • Disable the WebLocks API
  • Disable WebSpeech API

Safari 16.4 now supports dark mode for plain text files. It has support for smooth key-driven scrolling on macOS. And it adds prevention of redirects to data: or about: URLs.

In addition to the 135 new features, WebKit for Safari 16.4 includes an incredible amount work polishing existing features. We’ve heard from you that you want to know more about the many fixes going into each release of Safari. We’ve done our best to list everything that might be of interest to developers, in this case, 280 of those improvements:

  • Fixed -webkit-mask-box-image: initial to set the correct initial value.
  • Fixed -webkit-radial-gradient parsing accidentally treating several mandatory commas as optional.
  • Fixed ::placeholder to not support writing-mode , direction , or text-orientation.
  • Fixed @supports to not work if not , or , or and isn’t followed by a space.
  • Fixed background-repeat not getting correctly exposed through inline styles.
  • Fixed baseline-shift to allow length or percentage, but not numbers.
  • Fixed contain: inline-size for replaced elements.
  • Fixed CSSPerspective.toMatrix() to throw a TypeError if its length is incompatible with the px unit.
  • Fixed cx , cy , x , and y CSS properties to allow length or percentage, but not numbers.
  • Fixed filter: blur on an absolutely positioned image losing overflow: hidden .
  • Fixed font-face to accept ranges in reverse order, and reverse them for computed styles.
  • Fixed font-style: oblique must allow angles equal to 90deg or -90deg.
  • Fixed font-style: oblique with calc() to allow out-of-range angles and clamp them for computed style.
  • Fixed font-weight to clamp to 1 as a minimum.
  • Fixed font shorthand to reject out-of-range angles for font-style .
  • Fixed font shorthand to reset more longhand properties.
  • Fixed overflow-x: clip causing a sibling image to not load.
  • Fixed overflow: clip not working on SVG elements.
  • Fixed stroke-dasharray parsing to align with standards.
  • Fixed stroke-width and stroke-dashoffset parsing to align with standards.
  • Fixed text-decoration-thickness property not repainting when changed.
  • Fixed allowing calc() that combines percentages and lengths for line-height .
  • Fixed an issue where using box-sizing: border-box causes the calculated aspect-ratio to create negative content sizes.
  • Fixed an issue with a monospace font on a parent causing children with a sans-serif font using rem or rlh units to grow to a larger size.
  • Fixed behavior of cursor: auto over links.
  • Fixed buttons with auto width and height to not set intrinsic margins.
  • Fixed calculating block size to use the correct box-sizing with aspect ratio.
  • Fixed cells overflowing their contents when a table cell has inline children which change writing-mode .
  • Fixed clipping perspective calc() values to 0.
  • Fixed font shorthand to not reject values that happen to have CSS-wide keywords as non-first identifiers in a font family name.
  • Fixed hit testing for double-click selection on overflowing inline content.
  • Fixed honoring the content block size minimum for a <fieldset> element with aspect-ratio applied.
  • Fixed incorrectly positioned line break in contenteditable with tabs.
  • Fixed invalidation for class names within :nth-child() selector lists.
  • Fixed omitting the normal value for line-height from the font shorthand in the specified style, not just the computed style.
  • Fixed pseudo-elements to not be treated as ASCII case-insensitive.
  • Fixed rejecting a selector argument for :nth-of-type or :nth-last-of-type .
  • Fixed serialization order for contain .
  • Fixed strings not wrapped at zero width spaces when word-break: keep-all is set.
  • Fixed supporting <string> as an unprefixed keyframe name.
  • Fixed the :has() pseudo-selector parsing to be unforgiving.
  • Fixed the font-face src descriptor format to allow only specified formats, others are a parse error.
  • Fixed the tz component not accounting for zoom when creating a matrix3d () value.
  • Fixed the computed value for stroke-dasharray to be in px .
  • Fixed the effect of the writing-mode property not getting removed when the property is removed from the root element.
  • Fixed the position of text-shadow used with text-combine-upright .
  • Fixed the title of a style element with an invalid type to never be added to preferred stylesheet set.
  • Fixed the transferred min/max sizes to be constrained by defined sizes for aspect ratio.
  • Fixed the user-agent stylesheet to align hidden elements, abbr , acronym , marquee , and fieldset with HTML specifications.
  • Fixed to always use percentages for computed values of font-stretch , never keywords.
  • Fixed to not require whitespace between of and the selector list in :nth-child or :nth-last-child .
  • Fixed CSS.supports returning false for custom properties.
  • Fixed CSS.supports whitespace handling with !important .
  • Fixed forgiving selectors to not be reported as supported with CSS.supports("selector(...)") .
  • Fixed getComputedStyle() to return a function list for the transform property.
  • Fixed linear-gradient keyword values not getting converted to their rgb() equivalents for getComputedStyle() .

Content Security Policy

  • Fixed updating the Content Security Policy when a new header is sent as part of a 304 response.
  • Fixed <input type="submit"> , <input type="reset">, and <input type="button"> to honor font-size , padding , height , and work with multi-line values.
  • Fixed firing the change event for <input type="file"> when a different file with the same name is selected.
  • Fixed preventing a disabled <fieldset> element from getting focus.
  • Fixed the :out-of-range pseudo class matching for empty input[type=number] .
  • Fixed Array.prototype.indexOf constant-folding to account for a non-numeric index.
  • Fixed Intl.NumberFormat useGrouping handling to match updated specs.
  • Fixed Intl.NumberFormat ignoring maximumFractionDigits with compact notation.
  • Fixed String.prototype.includes incorrectly returning false when the string is empty and the position is past end of the string.
  • Fixed toLocaleLowerCase and toLocaleUpperCase to throw an exception on an empty string.
  • Fixed aligning the parsing of <body link vlink alink> to follow standards.
  • Fixed <legend> to accept more display property values than display: block .

Intelligent Tracking Prevention

  • Fixed user initiated cross-domain link navigations getting counted as Top Frame Redirects.
  • Fixed some display issues with HDR AVIF images.
  • Fixed the accept header to correctly indicate AVIF support.

Lockdown Mode

  • Fixed common cases of missing glyphs due to custom icon fonts.
  • Fixed enumerateDevices may return filtered devices even if page is capturing.
  • Fixed MediaRecorder.stop() firing an additional dataavailable event with bytes after MediaRecorder.pause() .
  • Fixed duplicate timeupdate events.
  • Fixed limiting DOMAudioSession to third-party iframes with microphone access.
  • Fixed MSE to not seek with no seekable range.
  • Fixed mute microphone capture if capture fails to start because microphone is used by a high priority application.
  • Fixed not allowing text selection to start on an HTMLMediaElement.
  • Fixed only requiring a transient user activation for Web Audio rendering.
  • Fixed screen capture to fail gracefully if the window or screen selection takes too long.
  • Fixed switching to alternate <source> element for AirPlay when necessary.
  • Fixed the local WebRTC video element pausing after bluetooth audioinput is disconnected.
  • Fixed trying to use low latency for WebRTC HEVC encoder when available.
  • Fixed unmuting a TikTok video pauses it.
  • Fixed WebVTT styles not applied with in-band tracks.
  • Ensured negative letter-spacing does not pull content outside of the inline box
  • Fixed <div> with border-radius not painted correctly while using jQuery’s .slideToggle() .
  • Fixed border-radius clipping on composited layers.
  • Fixed box-shadow to paint correctly on inline elements.
  • Fixed box-shadow invalidation on inline boxes.
  • Fixed calculating the width of an inline text box using simplified measuring to handle fonts with Zero Width Joiner , Zero Width Non-Joner , or Zero Width No-Break Space .
  • Fixed clearing floats added dynamically to previous siblings.
  • Fixed clipping the source image when the source rectangle is outside of the source image in canvas.
  • Fixed CSS keyframes names to not allow CSS wide keywords.
  • Fixed elements with negative margins not avoiding floats when appropriate.
  • Fixed floating boxes overlapping with their margin boxes.
  • Fixed HTMLImageElement width and height to update layout to return styled dimensions not the image attributes.
  • Fixed ignoring nowrap on <td nowrap="nowrap"> when an absolute width is specified.
  • Fixed incorrect clipping when a layer is present between the column and the content layer.
  • Fixed incorrect static position of absolute positioned elements inside relative positioned containers.
  • Fixed layout for fixed position elements relative to a transformed container.
  • Fixed layout overflow rectangle overflows interfering with the scrollbar.
  • Fixed negative shadow repaint issue.
  • Fixed preventing a focus ring from being painted for anonymous block continuations.
  • Fixed recalculating intrinsic widths in the old containing block chain when an object goes out of flow.
  • Fixed rendering extreme border-radius values.
  • Fixed specified hue interpolation method for hues less than 0 or greater than 360.
  • Fixed tab handling in right-to-left editing.
  • Fixed text selection on flex and grid box items.
  • Fixed the position and thickness of underlines to be device pixel aligned.
  • Fixed transforms for table sections.
  • Fixed transition ellipsis box from “being a display box on the line” to “being an attachment” of the line box.
  • Fixed unexpected overlapping selection with tab in right-to-left context.
  • Fixed updating table rows during simplified layout.
  • Fixed: improved balancing for border, padding, and empty block content.
  • Extensions that request the unlimitedStorage permission no longer need to also request storage .
  • Fixed browser.declarativeNetRequest namespace is now available when an extension has the declarativeNetRequestWithHostAccess permission.
  • Fixed isUrlFilterCaseSensitive declarativeNetRequest rule condition to be false by default.
  • Fixed tabs.onUpdated getting called on tabs that were already closed.
  • Fixed background service worker failing to import scripts.
  • Fixed content scripts not injecting into subframes when extension accesses the page after a navigation.
  • Fixed CORS issue when doing fetch requests from a background service worker.
  • Fixed declarativeNetRequest errors not appearing correctly in the extension’s pane of Safari Settings.
  • Fixed display of extension cookie storage in Web Inspector. Now the extension name is shown instead of a UUID.
  • Fixed declarativeNetRequest rules not loading when an extension is turned off and then on.
  • Fixed result of getMatchedRules() to match other browsers.
  • Fixed browser.webNavigation events firing for hosts where the extension did not have access.
  • Removed Keyboard Shortcut conflict warnings for browser.commands when there are multiple commands without keyboard shortcuts assigned.
  • Fixed overscroll-behavior: none to prevent overscroll when the page is too small to scroll.
  • Fixed <svg:text> to not auto-wrap.
  • Fixed preserveAspectRatio to stop accepting defer .
  • Fixed SVG.currentScale to only set the page zoom for a standalone SVG.
  • Fixed svgElement.setCurrentTime to restrict floats to finite values.
  • Fixed applying changes to fill with currentColor to other colors via CSS.
  • Fixed changes to the filter property getting ignored.
  • Fixed CSS and SVG filters resulting in a low quality, pixelated image.
  • Fixed focusability even when tab-to-links is enabled for <svg:a> .
  • Fixed handling animation freezes when repeatDur is not a multiple of dur .
  • Fixed making sure computed values for baseline-shift CSS property use px unit for lengths.
  • Fixed not forcing display: table-cell , display: inline-table , display: table , and float: none on table cell elements when in quirks mode.
  • Fixed removing the visual border when the table border attribute is removed.
  • Fixed font-optical-sizing: auto having no effect in Safari 16.
  • Fixed directionality of the <bdi> and <input> elements to align with HTML specifications.
  • Fixed handling an invalid dir attribute to not affect directionality.
  • Fixed the default oblique angle from 20deg to 14deg .
  • Fixed the handling of <bdo> .
  • Fixed the order of how @font-palette-values override-colors are applied.
  • Fixed @keyframes rules using an inherit value to update the resolved value when the parent style changes.
  • Fixed Animation.commitStyles() triggering a mutation even when the styles are unchanged.
  • Fixed Animation.startTime and Animation.currentTime setters support for CSSNumberish values.
  • Fixed baseline-shift animation.
  • Fixed baselineShift inherited changes.
  • Fixed commitStyles() failing to commit a relative line-height value.
  • Fixed getKeyframes() serialization of CSS values for an onkeyframe sequence.
  • Fixed rotate: x and transform: rotate(x) to yield the same behavior with SVGs.
  • Fixed word-spacing to support animating between percentage and fixed values.
  • Fixed accounting for non-inherited CSS variables getting interpolated for standard properties on the same element.
  • Fixed accumulating and clamping filter values when blending with "none" .
  • Fixed accumulation support for the filter property.
  • Fixed additivity support for the filter property.
  • Fixed animation of color list custom properties with iterationComposite .
  • Fixed blend transform when iterationComposite is set to accumulate .
  • Fixed blending to account for iterationComposite .
  • Fixed Calculating computed keyframes for shorthand properties.
  • Fixed composite animations to compute blended additive or accumulative keyframes for in-between keyframes.
  • Fixed computing the keyTimes index correctly for discrete values animations.
  • Fixed CSS animations participation in the cascade.
  • Fixed custom properties to support interpolation with a single keyframe.
  • Fixed filter values containing a url() should animate discretely.
  • Fixed interpolating custom properties to take iterationComposite into account.
  • Fixed jittering when animating a rotated image.
  • Fixed keyframes to be recomputed if a custom property registration changes.
  • Fixed keyframes to be recomputed if the CSS variable used is changed.
  • Fixed keyframes to be recomputed when bolder or lighter is used on a font-weight property.
  • Fixed keyframes to be recomputed when a parent element changes value for a custom property set to inherit .
  • Fixed keyframes to be recomputed when a parent element changes value for a non-inherited property set to inherit .
  • Fixed keyframes to be recomputed when the currentcolor value is used on a custom property.
  • Fixed keyframes to be recomputed when the currentcolor value is used.
  • Fixed opacity to use unclamped values for from and to keyframes with iterationComposite .
  • Fixed running a transition on an inherited CSS variable getting reflected on a standard property using that variable as a value.
  • Fixed seamlessly updating the playback rate of an animation.
  • Fixed setting iterationComposite should invalidate the effect.
  • Fixed setting the transition-property to none does not disassociate the CSS Transition from owning the element.
  • Fixed the composite operation of implicit keyframes for CSS Animations to return "replace" .
  • Fixed the timing model for updating animations and sending events.
  • Fixed updating timing to invalidate the effect.
  • Fixed -webkit-user-select: none allowing text to be copied to clipboard.
  • Fixed contentEditable caret getting left aligned instead of centered when the :before pseudo-element is used.
  • Fixed Cross-Origin-Embedder-Policy incorrectly blocking scripts on cache hit.
  • Fixed CSSRule.type to not return values greater than 15.
  • Fixed document.open() to abort all loads when the document is navigating.
  • Fixed document.open() to remove the initial about:blank -ness of the document.
  • Fixed Element.querySelectorAll not obeying element scope with ID.
  • Fixed FileSystemSyncAccessHandle write operation to be quota protected.
  • Fixed getBoundingClientRect() returning the wrong value for <tr> , <td> , and its descendants for a vertical table.
  • Fixed HTMLOutputElement.htmlFor to make it settable.
  • Fixed queryCommandValue("stylewithcss") to always return an empty string.
  • Fixed StorageEvent.initStorageEvent() to align with HTML specifications.
  • Fixed textContent leaving dir=auto content in the wrong direction.
  • Fixed -webkit-user-select: initial content within -webkit-user-select: none should be copied
  • Fixed WorkerGlobalScope.isSecureContext to be based on the owner’s top URL, not the owner’s URL.
  • Fixed a bug where mousedown without mouseup in a frame prevents a click event in another frame.
  • Fixed a sometimes incorrect location after exiting mouse hover.
  • Fixed accepting image/jpg for compatibility.
  • Fixed adding a non-breaking space, instead of a plain space, when it is inserted before an empty text node.
  • Fixed behavior of nested click event on a label element with a checkbox.
  • Fixed BroadcastChannel in a SharedWorker when hosted in a cross-origin iframe.
  • Fixed calculation of direction for text form control elements with dir="auto" .
  • Fixed canvas fallback content focusability computation.
  • Fixed deleting a button element leaving the button’s style in a contenteditable element.
  • Fixed disconnected <fieldset> elements sometimes incorrectly matching :valid or :invalid selectors.
  • Fixed dragging the mouse over a -webkit-user-select: none node can begin selection in another node.
  • Fixed ensuring nested workers get controlled if matching a service worker registration.
  • Fixed errors caught and reported for importScripts() .
  • Fixed escaping “&” in JavaScript URLs for innerHTML and outerHTML .
  • Fixed EventSource to stop allowing trailing data when parsing a retry delay.
  • Fixed Fetch Request object to keep its Blob URL alive.
  • Fixed filled text on a canvas with a web font refreshing or disappearing.
  • Fixed find on page failing to show results in PDFs.
  • Fixed firing an error event when link preload fails synchronously.
  • Fixed form submissions to cancel JavaScript URL navigations.
  • Fixed handing the onerror content attribute on body and frameset elements.
  • Fixed handling opaque origin Blob URLs.
  • Fixed handling text documents to align to modern HTML specifications.
  • Fixed handling the onerror content attribute on <body> and <frameset> elements.
  • Fixed HTMLTemplateElement to have a shadowRootMode attribute.
  • Fixed including alternate stylesheets in document.styleSheets .
  • Fixed incorrect caret movement in some right-to-left contenteditable elements.
  • Fixed incorrect color for videos loaded in a canvas.
  • Fixed incorrect image srcset candidate chosen for <img> cloned from <template> .
  • Fixed incorrectly ignored X-Frame-Options HTTP headers with an empty value.
  • Fixed lazy loading images sometimes not loading.
  • Fixed link elements to be able to fire more than one load or error event.
  • Fixed loading Blob URLs with a fragment from opaque, unique origins.
  • Fixed maintaining the original Content-Type header on a 303 HTTP redirect.
  • Fixed module scripts to always decode using UTF-8.
  • Fixed MouseEventInit to take movementX and movementY .
  • Fixed not dispatching a progress event when reading an empty file or blob using the FileReader API.
  • Fixed not replacing the current history item when navigating a cross-origin iframe to the same URL.
  • Fixed overriding the mimetype for an XHR.
  • Fixed parsing of negative age values in CORS prefetch responses.
  • Fixed pasting of the first newline into text area.
  • Fixed preventing selection for generated counters in ordered lists.
  • Fixed Safari frequently using stale cached resources despite using Reload Page From Origin.
  • Fixed scheduling a navigation to a Blob URL to keep the URL alive until the navigation occurs.
  • Fixed sending Basic authentication via XHR using setRequestHeader() when there is an existing session.
  • Fixed setting style="" to destroy the element’s inline style.
  • Fixed setting the tabIndex of a non-focusable HTMLElement.
  • Fixed system colors not respecting inherited color-scheme values.
  • Fixed textarea placeholder text not disappearing when text is inserted without a user gesture.
  • Fixed the event.keyIdentifier value for F10 and F11 keys.
  • Fixed the click event to not get suppressed on textarea resize.
  • Fixed the computed value for the transform property with SkewY .
  • Fixed the initialization of color properties.
  • Fixed timing of ResizeObserver and IntersectionObserver to match other browsers.
  • Fixed toggling a details element when a summary element receives a click() .
  • Fixed updating Text node children of an option element to not reset the selection of the select element.
  • Fixed using NFC Security Key on iOS.
  • Fixed using WebAuthn credentials registered on iOS 15 if iCloud Keychain is disabled.
  • Fixed WebAuthn sending Attestation as None when requested as Direct.
  • Fixed XHR aborting to align with standards specification
  • Fixed XHR error events to return 0 for loaded and total.
  • Fixed: Made all FileSystemSyncAccessHandle methods synchronous.
  • Fixed: Removed the precision="float" attribute on <input type="range"> .
  • Fixed video textures set to repeat.
  • Fixed “Inspect Element” not highlighting the element.
  • Fixed capturing async stack traces for queueMicrotask .
  • Fixed clicking coalesced events in the timeline selecting the wrong event.
  • Fixed event breakpoints to support case-insensitive and RegExp matching.
  • Fixed slow search with a lot of files in the Open Resource dialog.
  • Fixed sorting prefixed properties below non-prefixed properties in the Computed panel of the Elements Tab.
  • Fixed the always empty Attributes section in the Node panel of the Elements Tab.
  • Fixed the Computed Tab scrolling to the top when a <style> is added to the page.
  • Fixed URL breakpoints to also pause when HTML attributes are set that trigger loads.
  • Fixed “Get Element Rect” to not round to integer values.
  • Fixed automation sessions terminating during navigation.
  • Fixed click element failing on iPad when Stage Manager is disabled.
  • Fixed HTTP GET requests with a body failing.
  • Fixed the Shift modifier key not applying to typed text.

We love hearing from you. Send a tweet to @webkit to share your thoughts on Safari 16.4. Find us on Mastodon at @[email protected] and @[email protected] . If you run into any issues, we welcome your feedback on Safari UI, or your WebKit bug report about web technology or Web Inspector. Filing issues really does make a difference.

Download the latest Safari Technology Preview to stay at the forefront of the web platform and to use the latest Web Inspector features. You can also read the Safari 16.4 release notes .

More than 3 years have passed since last update.

input type file safari

Safariのinput type="file"で問題が繰り返し起きるときの対応

ファイルアップロードは、かなり鉄板機能なので実装することが多いのですが、ハマりかけたのでログに残しておきます。

ファイルアップロードのソースは、雰囲気こんな感じです。

inputタグをそのまま使うとダサいので、style="display: none"にして、その代わりにボタンやフォームのクリックイベントでinputタグのクリックイベントを発火します。

開発が一段落し、自分のiPhoneでぽちぽちやっていると、こんな現象に遭遇しました。

問題が起きたため、このWebページが再読込されました。 XXXXXXXXで問題が繰り返し起きました。

Safariでは、display:noneに問題があるらしいです。なので、 『inputタグはdisplay:noneではなく、divで囲んでheightとwidthを0にせよ』 とのことでした。

う〜ん何故だろう、、、 むかしからdisplay:noneが常識かつ定石だと思っていましたら、Safariさんは違ったようです。

Safari input='file' doesn't work

Register as a new user and use Qiita more conveniently

  • You get articles that match your needs
  • You can efficiently read back useful information
  • You can use dark theme

IMAGES

  1. How can one use in Safari on iPhone?

    input type file safari

  2. Html input types style

    input type file safari

  3. ios

    input type file safari

  4. Input type FILE on HTML FORM not working on Safari Version 14.0.1

    input type file safari

  5. iOS、Safariの で発生するエラーに対応した際の備忘録

    input type file safari

  6. Selecting files for input Safari applescript

    input type file safari

VIDEO

  1. Input Type

  2. Custom File Upload Button CSS

  3. Upload Image With Preview Image

  4. File Input Button With Image Preview & File Name

  5. Custom Input Type File Upload Button Using HTML & CSS

  6. HTML5 and JavaScript: How to use the file input control

COMMENTS

  1. html

    1. Indeed it seems Safari doesn't accept files' extensions as accept attribute... And it could be seen as a bug since they will do the MIME detection against this exact file extension...) The only workaround I see for now, is to use the full MIME type. But this may lead to some problem where some browsers will use the OS's MIME types dictionary ...

  2. <input type="file">

    A unique file type specifier is a string that describes a type of file that may be selected by the user in an <input> element of type file. Each unique file type specifier may take one of the following forms: A valid case-insensitive filename extension, starting with a period (".") character. For example: .jpg, .pdf, or .doc.

  3. html input type file don't work

    I upgraded to Safari 14.0.1 (14610.2.11.51.10) in Mojave and suddenly html input type file tags stopped working. It seems to deny file access when the button is clicked.

  4. Supported Input Values

    Input Type Values. Safari supports many different input types. They can be specified using the type attribute of the input element. These input types are listed below. ... A file upload interface. hidden. A hidden input type (to store values without showing them on the page). Note that the input can still be seen in the page source.

  5. <input type="file">

    It may look similar, but if you try selecting a file with this input, you'll see that the file picker only lets you select the file types specified in the accept value (the exact nature differs across browsers and operating systems).. The accept attribute doesn't validate the types of the selected files — it provides hints for browsers to guide users towards selecting the correct file types.

  6. <input>: The Input (Form Input) element

    accept. Valid for the file input type only, the accept attribute defines which file types are selectable in a file upload control. See the file input type.. alt. Valid for the image button only, the alt attribute provides alternative text for the image, displaying the value of the attribute if the image src is missing or otherwise fails to load. See the image input type.

  7. HTML input accept Attribute

    The accept attribute specifies a filter for what file types the user can pick from the file input dialog box. Note: The accept attribute can only be used with. <input type="file">. Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.

  8. Using HTML File Input for Uploading Native iOS/Android Files

    The standard <input type="file"> element provides a surprisingly smooth file selection experience on native iOS and Android platforms, and these files can be easily sent as standard multipart/form-data to your backend server. This will probably be all you need a lot of the time, but for certain specialised circumstances or use cases you might ...

  9. accept attribute for file input

    accept attribute for file input. Allows a filter to be defined for what type of files a user may pick with from an <input type="file"> dialog. Not supported means any file can be picked as if the accept attribute was not set, unless otherwise noted. On Windows, files that do not apply are hidden. On OSX they are grayed out and disabled.

  10. input type="file" automatically co…

    above a certain capacity. No conversion occurs at lower capacity. However, the criteria for conversion seems to vary from file format to file format. In the case of jpeg, the conversion occurred if it exceeded 10MB, but in the case of png, the conversion occurred only when it exceeded 20MB. Image I/O.

  11. Input File don`t work on IOS

    Input File don`t work on IOS You're now watching this thread. If you've opted in to email or web notifications, you'll be notified when there's activity.

  12. Custom styled input type file upload button with pure CSS

    To upload files you'll need to use the input tag with type="file" attribute. Additionally you can specify which file types you're allowing to upload via accept attribute. HTML: <input type="file" accept="image/*">. This markup produces a button with a Choose file title followed by a text which indicates the file name when selected.

  13. Understanding input types in Shortcuts on iPhone or iPad

    You can specify which input types the shortcut can accept. The default input type is Any, which allows the shortcut to appear in any app. When you change input types, the shortcut appears only in apps that share the specified type of content. For example, a shortcut that accepts only URLs appears when you run the shortcut from Safari, but does ...

  14. HTML Input Types

    Input Type Hidden. The <input type="hidden"> defines a hidden input field (not visible to a user).. A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted. A hidden field often stores what database record that needs to be updated when the form is submitted.

  15. HTML input type="file"

    The <input type="file"> defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files to be selected, add the multiple attribute. Tip: Always add the <label> tag for best accessibility practices! Browser Support.

  16. WebKit Features in Safari 16.4

    Safari 16.4 also includes two improvements for <input type="file">. Now a thumbnail of a selected file will appear on macOS. And the cancel event is supported. JavaScript and WebAssembly. Safari 16.4 brings a number of useful new additions for developers in JavaScript and WebAssembly.

  17. javascript file input onchange not working [ios safari only]

    Found out that using addEventListener is indeed required. Adding it to the body alone is not sufficient. For whatever reason iOS Safari does not fire .onchange for photos taken directly with the camera (i.e., using the take photo option). It does, strangely, fire .onchange for photos taken from the photo library, which made me not realize the take photo option was failing for a while.

  18. Safariのinput type="file"で問題が繰り返し起きるときの対応

    Safariでは、display:noneに問題があるらしいです。 なので、 『inputタグはdisplay:noneではなく、divで囲んでheightとwidthを0にせよ』 とのことでした。 < template > <!--

  19. JS

    The workaround I'm using is to detect when the new type will be file and in this special case, create a new input element, set its type to file, set its id and replace the existing input with the new one. var input = $('#input'); $('button[id^=type-]').on('click', function() {. var type = $(this).attr('id').replace('type-', '');