feat(api): add convertFileSrc helper (#2138)

This commit is contained in:
Lucas Fernandes Nogueira 2021-07-02 00:00:30 -03:00 committed by GitHub
parent 06abe65569
commit 51a5cfe4b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 35 additions and 7 deletions

View File

@ -0,0 +1,5 @@
---
"api": patch
---
Adds `convertFileSrc` helper to the `tauri` module, simplifying the process of using file paths as webview source (`img`, `video`, etc).

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -79,10 +79,10 @@
}
],
"security": {
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: asset: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
},
"systemTray": {
"iconPath": "../../.icons/icon.png"
}
}
}
}

View File

@ -1,9 +1,11 @@
<script>
import { readBinaryFile, readDir, Dir } from "@tauri-apps/api/fs";
import { convertFileSrc } from "@tauri-apps/api/tauri";
export let onMessage;
let pathToRead = "";
let img;
function getDir() {
const dirSelect = document.getElementById("dir");
@ -71,6 +73,10 @@
})
.catch(onMessage);
}
function setSrc() {
img.src = convertFileSrc(pathToRead)
}
</script>
<form on:submit|preventDefault={read}>
@ -86,4 +92,7 @@
bind:value={pathToRead}
/>
<button class="button" id="read">Read</button>
<button class="button" type="button" on:click={setSrc}>Use as img src</button>
<img alt="file" bind:this={img}>
</form>

View File

@ -88,6 +88,20 @@ async function invoke<T>(cmd: string, args: InvokeArgs = {}): Promise<T> {
})
}
/**
* Convert a device file path to an URL that can be loaded by the webview.
* Note that `asset:` must be allowed on the `csp` value configured on `tauri.conf.json`.
*
* @param filePath the file path. On Windows, the drive name must be omitted, i.e. using `/Users/user/file.png` instead of `C:/Users/user/file.png`.
*
* @return the URL that can be used as source on the webview
*/
function convertFileSrc(filePath: string): string {
return navigator.userAgent.includes('Windows')
? `https://custom.protocol.asset_${filePath}`
: `asset://${filePath}`
}
export type { InvokeArgs }
export { transformCallback, invoke }
export { transformCallback, invoke, convertFileSrc }