Is there a way to load local files into HTML in Electron? Getting ERR_UNKNOWN_URL_SCHEME - electron

I have an Electron app that's trying to load a local audio file into an HTML5 <audio> element. The path itself is fine file:///../song.mp3 and I've set webSecurity to false, but I'm still getting Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME. From that same error, if I copy the address and paste it into my browser, I get the correct file.
Are there any other settings I need to change to get this to work?
Appreciate your time

I think this is a bug. The URL scheme of the file is not enabling as a URL scheme.
You can use this code below inside of app.on('ready'....:
protocol.registerFileProtocol('file', (request, cb) => {
const url = request.url.replace('file:///', '')
const decodedUrl = decodeURI(url)
try {
return cb(decodedUrl)
} catch (error) {
console.error('ERROR: registerLocalResourceProtocol: Could not get file path:', error)
}
})
it will be fixed

Related

IOS iPhone browsers does not accept video files via upload dialog

We are using IOS file upload dialog in order to use video files with our service using react.
All video files are working in android platforms and all browsers in linux and MacOS. However, when we use video files with upload dialog in IOS IPhones such as Iphone 14 Pro Max, then the compress process starts and following that the dialog rejects the video file.
We have been debugging with browserstack using a real phone in a simulator, however no luck until this point.
When we select the file, it firstly runs a compression activity then changes the name of the file to an intermediate file name (as below, the original file name is different), and then upload procedure fails.
Below is the react part which triggers upload mechanism which works with every platform and operating system with exception of IOS.
export const UploadVideo = async (file, signedurl, uploading) =>
{
let resultState = { state: '', data: {} };
if (SERVER_STATUS !== 'localhost')
{
await axios({
method: 'put',
url: signedurl,
data: file,
headers: { 'Content-Type': 'application/octet-stream', },
onUploadProgress: uploading
}).then(function (response)
{
resultState.state = 'success';
}).catch(function (error)
{
resultState.state = 'error';
resultState.data.message = error.message;
window.toastr.error(error.message);
})
} else resultState.state = 'success';
return resultState;
}
The error message I notice here, OS Status error -9806 refers to, according to osstatus.com a secure transport result code. More specifically this one, on Apple's documentation
My take here is that the system is not trusting this URL, I would suggest adding your URL to trusted domains under NSAppTransportSecurity in the Info.plist file. More info on how to do that here.
This is not a solution I would go for for a production app tho, you might want to have a valid certificate for your production URL and app.
Hope this helps.

"Not allowed to load local resource" with file image URL in Electron app

I am working on a note taking Electron app that uses Markdown. Currently, I'm working on inserting images into notes (using the Markdown syntax).
When inserting an image, my main process copies the image into the notes directory, then returns a file:/// URL to the image file. However, when I try to render the image, it doesn't load - and I get the error Not allowed to load local resource: file:///Users/joe/notes/images/foo.jpg.
Is there a way I can configure Electron to allow these local image URLs?
Option 1
Turning the web security off
mainWindow = new BrowserWindow({
height: 563,
useContentSize: true,
width: 1000,
webPreferences: {
webSecurity: false
}
});
Option 2
You can create your own protocol like this answer
Also here is the user that answered that question
You need register a file protocol to remove the file:/// prefix.
import { protocol } from "electron";
app.whenReady().then(() => {
protocol.registerFileProtocol('file', (request, callback) => {
const pathname = decodeURI(request.url.replace('file:///', ''));
callback(pathname);
});
});
https://github.com/electron/electron/issues/23757#issuecomment-640146333

Sent a file from backend to frontend. Cannot restore its old form

here I have a function that reacts to a button click
and gains a file from my backend.
onDownload() {
this.http.get('http://localhost:8080/backend/invoice/1/download',
{responseType: 'blob'})
.subscribe(res =>
console.log(res))
}
So far, I am happy because inside the chrome console I dont get any errors.
The response looks like this in the console:
The return type of the Java backend was InputStream (method annotation #Produces(MediaType.MULTIPART_FORM_DATA))
Then I found
https://stackblitz.com/edit/angular-blob-file-download?file=app%2Fapp.component.ts
and looked at ngOnInit() in app.component.ts
ngOnInit() {
const data = 'some text';
const blob = new Blob([data], { type: 'application/octet-stream' });
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
}
Currently, I think my frontend receives a blob.
So, I can start in the line starting with "this.fileUrl="
and input my blob.
Inside the .html, I have a button to start the onDownload() function
and another tag to save the file on my local hard drive.
<div>
<button (click)="onDownload()">Herunterladen</button>
</div>
<a [href]="safeResourceUrl" download="file.txt">DownloadFile</a>
Meanwhile, I change the onDownload() method to
onDownload() {
this.http.get('http://localhost:8080/backend/invoice/1/download',
{responseType: 'blob'})
.subscribe(res => this.safeResourceUrl=this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(res)))
}
After I click "Herunterladen" and then the DownloadFile link I get either
a .txt file that I cannot read
or, if I change the file name to .pdf in the a tag inside the .html,
I get a "failed to load pdf document"
All I want is to get my original pdf that I stored in my database and that was sent from the backend.
Has anyone had the same problem before? Thank you for your help.
I changed my function to
onDownload() {
window.open(`http://localhost:8080/backend/invoice/${this.invoice.invoiceNr}/download`, 'blank');
}
Now it works:)

How to get file from URI | Expo | React Native

I have ejected project of the expo.
After changing info.plist, now I am able to get my app in the list of "open with app list" and actually able to open that file with my expo(React native app).
App.js
Linking.getInitialURL().then((url) => {
if (url) {
console.log(url);
}
}).catch(err => console.error('An error occurred', err));
this code is giving me this URL.
file:///private/var/mobile/Containers/Data/Application/7E55EB55-7C49-4C0C-B4CB-63AC4F49689E/Documents/Inbox/matters-3.csv
So, that means now I have URL of the email attachment, but How am I able to get the data of that csv string in my app?
So I am assuming, when I click open with my app. The URL that is passed into my app from the system is actually a copy of the document that is placed somewhere in our app’s directory.
But when I trying to access this file with Expo.FileSystem. readAsStringAsync it's giving me an error says, the file is not readable.
is there anything to do with storage permission?
Need Help....?
I think you could use react-native-fs. This here should work and print out the contents of the CSV file to the console.
App.js
var RNFS = require('react-native-fs');
Linking.getInitialURL().then((url) => {
if (url) {
RNFS.readFile(url).then((data) => {
console.log(data);
}
}).catch(err => console.error('An error occurred', err));
You can use react-native-fs as Carlo mentioned or rn-fetch-blob, I recommend rn-fetch-blob, to read a file u can check their documentation, it goes something like this
let data = '';
RNFetchBlob.fs.readStream( ...options).then((ifstream) => {
ifstream.open()
ifstream.onData((chunk) => {
data += chunk
// show progress ...%
})
ifstream.onError((err) => {
console.log('oops', err)
})
ifstream.onEnd(() => {
consol.log('final data', data)
})
}))

Fetch/XHR own files

My extension works in Chrome, Firefox, and Opera. I wanted to support edge too. However I cannot do a simple thing, I cannot fetch/XHR my own files! I even added <all_urls> to my permissions array in manifest.json, however I keep getting TypeMismatchError and in details it says "Permission Denied". Here is a screenshot:
Does anyone know if it is possible to fetch your own files in Edge? I need to specifically fetch the messages.json files in my /_locales/* folders.
This is a known issue which has been reported here https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8546263/, you can use the workaround mentioned in the link or use XMLHttpRequest instead of fetch.
const xhr = new XMLHttpRequest();
xhr.onload = () => {
console.log(xhr.responseText);
};
const url = chrome.runtime.getURL('test/test.js');
xhr.open("GET", url);
xhr.send();

Resources