I'm trying to use javascript to open a .pdf link on chrome for which I know the base URL and the beginning of the .pdf, however I'm missing the last caracters of the file.
I was thinking I could maybe loop through all the files located in the specific folder of the URL and check if one of them was starting like the file I wanted but couldn't get very far as I didn't succeed in getting the list of all filenames from that URL as I only found window.location.href but that doesn't refer to my URL but to where I'm at currently.
Even better I figured I could provide the start of an url with a wildcard and that it'd open the first document matching this, kind of the "like" in sql but it didn't work either.
StringToFind = "recordnumber123";
if(window.location.href.indexOf(stringToFind) > -1) {
filename = name_of_the_file_that_matched;
}
My base URL is something like:
"https://www.documents.com/records/"
my filenames are like
"recordnumber123_201810091102453651.pdf"
and I only know the part:
"recordnumber123" and that it is a .pdf.
The numbers after the underscore are added by the system as some sort of timestamp but I don't have a way to get them.
If this isn't possible, I also know the server on which these files are stored (for which I have the exact name) but I couldn't manage to open the file from chrome.
I tried to open it using
href="http://file://///https://www.documents.com/records/recordnumber123_201819124564.pdf"
but it redirects me to http://ww8.file.com/
and href="file://///https://www.documents.com/records/recordnumber123_201819124564.pdf"
but it doesn't launch anything. From what I read it seems that it's not allowed anymore to access files direclty like this from Chrome?
I can only use chrome and I cannot install specific plugins...
Related
I am going to deploy this page on an FTP
And I need to find out how I can detect the html file currently being viewed using JavaScript.
If I open the html file, it works just fine with this:
var fileName = location.href.substring(location.href.lastIndexOf("/") +1);
But, if I open it via my localhost adress, it has a null value. So I'm guessing I have to use some other method to extract the current html file name. Or is there a better approach to this?
Note: I am not going to use JQuery or anything like that.
EDIT:
I can get the filename if it isn't my index file.. If it's the index file I get nothing using the above code. Most likely since all I have in my adress bar is the localhost adress of the live-server?
The web deals in URLs, not file names.
Sometimes a URL will include something that looks like a file name, and sometimes that even maps on to a real file name on the server's hard disk.
When you type http://example.com/ then it might map that onto a file called index.html. Or maybe on to index.php. Or maybe it won't touch any file but will just use logic built into the web server application to determine what to respond with.
There's no way to know in the general case.
If your specific case, you know that the path / maps onto index.html, so you can write an explicit mapping in your JavaScript code.
I've converted an existing web application (HTML5, JS, CSS, etc.) into a Windows UWP app so that (hopefully) I can distribute it via the Windows Store to Surface Hubs so it can run offline. Everything is working fine, except PDF viewing. If I open a PDF in a new window, the Edge-based browser window simply crashes. If I open an IFRAME and load PDFJS into it, that also crashes. What I'd really like to do is just hand off the PDF to the operating system so the user can view it in whatever PDF viewer they have installed.
I've found some windows-specific Javascript APIs that seem promising, but I cannot get them to work. For example:
Windows.System.Launcher.launchUriAsync(
new Windows.Foundation.Uri(
"file:///"+
Windows.ApplicationModel.Package.current.installedLocation.path
.replace(/\//g,"/")+"/app/"+url)).then(function(success) {
if (!success) {
That generates a file:// URL that I can copy into Edge and it shows the PDF, so I know the URL stuff is right. However, in the application it does nothing.
If I pass an https:// URL into that launchUriAsync function, that works. So it appears that function just doesn't like file:// URLs.
I also tried this:
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(url).then(
function(file) { Windows.System.Launcher.launchFileAsync(file) })
That didn't work either. Again, no error. It just didn't do anything.
Any ideas of other things I could try?
-- Update --
See the accepted answer. Here is the code I ended up using. (Note that all my files are in a subfolder called "app"):
if (location.href.match(/^ms-appx:/)) {
url = url.replace(/\?.+/, "");
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(("app/" + url).replace(/\//g,"\\")).then(
function (file) {
var fn = performance.now()+url.replace(/^.+\./, ".");
file.copyAsync(Windows.Storage.ApplicationData.current.temporaryFolder,
fn).then(
function (file2) {
Windows.System.Launcher.launchFileAsync(file2)
})
});
return;
}
Turns out you have to turn the / into \ or it won't find the file. And copyAsync refuses to overwrite, so I just use performance.now to ensure I always use a new file name. (In my application, the source file names of the PDFs are auto-generated anyway.) If you wanted to keep the filename, you'd have to add a bunch of code to check whether it's already there, etc.
LaunchFileAsync is the right API to use here. You can't launch a file directly from the install directory because it is protected. You need to copy it first to a location that is accessible for the other app (e.g. your PDF viewer). Use StorageFile.CopyAsync to make a copy in the desired location.
Official SDK sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/AssociationLaunching
I just thought I'd add a variation on this answer, which combines some details from above with this info about saving a blob as a file in a JavaScript app. My case is that I have a BLOB that represents the data for an epub file, and because of the UWP content security policy, it's not possible simply to force a click on a URL created from the BLOB (that "simple" method is explicitly blocked in UWP, even though it works in Edge). Here is the code that worked for me:
// Copy BLOB to downloads folder and launch from there in Edge
// First create an empty file in the folder
Windows.Storage.DownloadsFolder.createFileAsync(filename,
Windows.Storage.CreationCollisionOption.generateUniqueName).then(
function (file) {
// Open the returned dummy file in order to copy the data to it
file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) {
// Get the InputStream stream from the blob object
var input = blob.msDetachStream();
// Copy the stream from the blob to the File stream
Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output).then(
function () {
output.flushAsync().done(function () {
input.close();
output.close();
Windows.System.Launcher.launchFileAsync(file);
});
});
});
});
Note that CreationCollisionOption.generateUniqueName handles the file renaming automatically, so I don't need to fiddle with performance.now() as in the answer above.
Just to add that one of the things that's so difficult about UWP app development, especially in JavaScript, is how hard it is to find coherent information. It took me hours and hours to put the above together from snippets and post replies, following false paths and incomplete MS documentation.
You will want to use the PDF APIs https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/PdfDocument/js
https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/PdfDocument/js/js/scenario1-render.js
Are you simply just trying to render a PDF file?
I'm working on an HTML/javascript app intended to be run locally.
When dealing with img tags, it is possible to set the src attribute to a file name with a relative path and thereby quickly and easily load an image from the app's directory. I would like to use a similar method to retrieve a text file from the app's directory.
I have used TideSDK, but it is less lightweight. And I am aware of HTTP requests, but if I remember correctly only Firefox has taken kindly to my use of this for local file access (although accessing local images with src does not appear to be an issue). I am also aware of the FileReader object; however, my interface requires that I load a file based on the file name and not based on a file-browser selection as with <input type="file">.
Is there some way of accomplishing this type of file access, or am I stuck with the methods mentioned above?
The browser will not permit you to access files like that but you can make javascript files instead of text files like this:
text1.js:
document.write('This is the text I want to show in here.'); //this is the content of the javascript file
Now call it anywhere you like:
<script type="text/javascript" src="text1.js"></script>
There are too many security issues (restrictions) within browsers making many local web-apps impossible to implement so my solution to a similar problem was to move out of browsers and into node-webkit which combines Chromium + Node.js + your scripts, into an executable with full disk I/O.
http://nwjs.io/
[edit] I'm sorry I thought you wanted to do this with TideSDK, I'll let my answer in case you want to give another try to TideSDK [/edit]
I'm not sure if it's what you're looking for but I will try to explain my case.
I've an application which allow the user to save the state of his progress. To do this, I allow him to select a folder, enter a filename and write this file. When the user open the app, he can open the saved file, and get back his progress. So I assume this enhancement is similar of what you are looking for.
In my case, I use the native File Select to allow the user to select a specific save (I'm using CoffeeScript) :
Ti.UI.currentWindow.openFileChooserDialog(_fileSelected, {
title: 'Select a file'
path: Ti.Filesystem.getDocumentsDirectory().nativePath()
multiple: false
})
(related doc http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.UI.UserWindow-method-openFileChooserDialog)
When this step is done I will open the selected file :
if !filePath?
fileToLoad = Ti.Filesystem.getFile(scope.fileSelected.nativePath())
else
fileToLoad = Ti.Filesystem.getFile(filePath)
data = Ti.JSON.parse(fileToLoad.read())
(related doc http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.Filesystem)
Please note that those snippets are copy/paste from my project and they will not work without the rest of my code but I think it's enough to illustrate you how I manage to open a file, and read his content.
In this case I'm using Ti.JSON.parse because there is only javascript object in these files but in your case you can just get the content. The openFileChooserDialog isn't mandatory, if you already know the file name, or if you get it from another way you can use Ti.Filesystem in your own way.
I have following url to be build,
http://localhost/myweb/cart/index.php
I want to get the http://localhost/myweb/ bit build dynamically.
To do that on my live web site which is http://www.myweb.com/cart/index.php I can use the following JavaScript code,
var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
But how do I get my development environment to work since it has http://localhost/myweb/? If I run the above code it will give me http://localhost/ only.
Any suggestions?
window.location.pathname is the thing you search for.
I would suggest you to read the MDN description of window.location. Like everything else in MDN, this is also really straightforward and informative.
If you know that the URL has an unnecessary index.html part at the end you can:
var path = window.location.pathname.split('/');
path.pop();
path.join('/');
or you can slice it (since it is generally faster):
path.slice(0,path.lastIndexOf('/')+1)
EDIT:
Seeing your new question I can say that what you want can't be done consistently and safely by only the current URL.
You need the http://localhost/myweb/ part, which is the URL root of your application. In javascript you are able to get the protocol and domain of the url. On your live site these 2 match, but if your application resides in a subfolder (like the myweb folder at your localhost), this will fail.
What you need is to somehow identify the application URL (the URL root of your application).
The problem is that by only examining the URL, javascript cannot tell where your application resides.
Let's say you deploy your site to: http://localhost/myweb/site1/
You will have the following URL: http://localhost/myweb/site1/cart/index.php
Javascript can split your URL by the slashes (/) but it has no way of nowing how many subfolders it should select. For example from the URL above your application root can be any of the following: http://localhost/, http://localhost/myweb/, http://localhost/myweb/site1/, http://localhost/myweb/site1/cart/.
By an other approach (which I suggested first) you can drop the end of the URL (in your case the cart/index.php part). This will only work if your URL structure IS very rigid, so all the pages this script is executed on reside in one subfolder.
So it will break on the following URL: http://localhost/myweb/site1/gallery/old/index.php or similar.
Your best bet would be to make this a "config variable" in a separate file which you edit on every location it is deployed to.
Either as a PHP variable ($appRoot = "http://localhost/myweb/") which you generate the javascript with.
Or more simply a javascript variable (var appRoot = 'http://localhost/myweb/'). Make a separate js file, call it something like config.js, add the above line to it and reference it before your other javascripts.
I know this has been asked plenty of times, but this is a special case. I'm working on an online HTML editor, using the design function of HTML 5 browsers (yeah, I found a useful application for this feature). I want to let the developer load a page, but developers are lazy (so am I), so I don't want them to enter the full path to their page. To prevent this, I use a file input (id="temp") WHICH DOESN'T GO TO THE SERVER!!!
I tried to open the local HTML file in a new browser in several ways, but the relative links in the page don't work:
window.open(temp.files.item(0)?temp.files.item(0).getAsDataURL():'',title.value,'width='+screen.width+',height='+screen.height)
The URL is encoded. This way the links in the file don't work, like in a ZIP file.
last = window.open('',title.value,'width='+screen.width+',height='+screen.height)
if(temp.files.item(0))
last.document.body.innerHTML = temp.files.item(0).getAsText("utf-8")
This code opens a blank page and copies the HTML code to the blank page. Of course the links in this page don't work either. temp.value only shows the filename, not the path.
Browsers simply will not tell you the information you want. The "value" property of "file" input elements does not contain the path.
If "the page" is really just an HTML page, then you might want to look into the HTML5 file reader stuff and see if you could at least read the file contents and dump them into a new browser window/tab. There might still be problems with HTML documents that expect to be able to locate auxiliary files (CSS, images, etc) via relative paths.