Webview loadUrl() from file on local storage (not assets) - javascript

I'm working on a code piece which must load html file to my custom webview. I'm moving my file out of assets to a local folder. And from there I need to read the html to a webview. I need to move the file from assets folder so please don't suggest anything about assets.
This is how I move files:
File f = new File(context.getFilesDir()+"/TMP/");
try {
String[] assets = {"editor.html", "normalize.css", "rich_editor.js", "style.css"};
for(String a : assets)
{
InputStream is = context.getAssets().open(a);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f + a);
fos.write(buffer);
fos.close();
}
} catch (FileNotFoundException e) { }
catch (IOException ex)
{
ex.printStackTrace();
}
This is how I'm trying to read it.
loadUrl("file://"+ new File(context.getFilesDir()+"/TMP/editor.html").getAbsolutePath());
I don't get an error or anything. But I do get a white screen and nothing else. I have thought that it might not be loading Javascript or CSS. But loading JS is enabled so it must work. Is any aditional editing required for html file due to moving it from one folder to another?
Update:
I know that the file is coppied successfully because I have checked it from inside the code and it's all good. I believe the problem is in the WebView method or linking.
I have also tried loadData and loadDataWithBaseURL(). Both work the same. Blank screen

Related

Display local html page in UWP WebView

I would like to display my local html page in a WebView. If I put my html page in the Application's local folder then I can point to it using the following code and it works:
webView.Navigate(new Uri("ms-appdata:///local/myHtmlPage.html"));
But I want to know if there is an equivalent Uri that takes my to the publisher cache folder? The reason I ask is I want to share the html page and it's data (files) between the applications I deploy. I have tried putting the html page in the publisher cache folder, then pointing the WebView's Navigate method to the html page's path but I can't get the WebView to open the page. I get some HRESULT exception with no details as to why it failed.
I want to open files in the html page without prompting the user to pick one and the only way I know how to do this is if the files are in a sub directory of the page's directory. I'll have a javascript function that opens the file using the path and I'll call this function from my UWP application and pass it the name of the file.
Help in this regard would be greatly appreciated.
Display local html page in UWP WebView
Sure, you could use StreamUriWinRTResolver to converter html file where in publisher folder to stream. And use WebView NavigateToLocalStreamUri to load that stream.
For example
public sealed class StreamUriWinRTResolver : IUriToStreamResolver
{
/// <summary>
/// The entry point for resolving a Uri to a stream.
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
if (uri == null)
{
throw new Exception();
}
string path = uri.AbsolutePath;
// Because of the signature of this method, it can't use await, so we
// call into a separate helper method that can use the C# await pattern.
return getContent(path).AsAsyncOperation();
}
/// <summary>
/// Helper that maps the path to package content and resolves the Uri
/// Uses the C# await pattern to coordinate async operations
/// </summary>
private async Task<IInputStream> getContent(string path)
{
// We use a package folder as the source, but the same principle should apply
// when supplying content from other locations
try
{
var filename = path.Remove(0, 1);
StorageFile f = await ApplicationData.Current.GetPublisherCacheFolder("Folder1").GetFileAsync(filename);
IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
return stream.GetInputStreamAt(0);
}
catch (Exception e)
{
throw new Exception("Invalid path");
}
}
}
Usage
Uri url = MyWebView.BuildLocalStreamUri("MyTag", "ContentPage.html");
StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
MyWebView.NavigateToLocalStreamUri(url, myResolver);

Getting Uncaught ReferenceError: camera is not defined

I have JS camera object in codenameone project while I am trying to call that object from a js file its giving me the Uncaught ReferenceError: camera is not defined
error in my chrome browser, while i am trying to upload a image
Below is my codenameone code
camera.set("capture",new JSFunction(){
public void apply(JSObject self, Object[] args) {
Display.getInstance().openImageGallery(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt) {
String imagePath ="";
if(evt!=null){
imagePath=(String)evt.getSource();
final JSObject uploadedFile = (JSObject)ctx.get("document.getElementById('uploadedFile')");
uploadedFile.set("value",imagePath);
}
}
});
}
});
ctx.set("camera", camera);
Below is my js file where i am getting error for the camera object I used to give window.camera but at that its giving the same above error for capture where capture is the button id which i am using in my html file.
Below is my js file
document.getElementById('capture')
.addEventListener('click', function(){
camera.capture(function(){
var results = document.getElementById("uploadedFile").value;
document.getElementById("uploadedFile").value=results;
})
}, true);
JS camera file is not loaded thats why you are getting this error.
Make sure file is loaded above this code.
structure should be like this-->
file src included
then-->
your script here
I'm guessing you are trying to access HTML5 API's within an embedded browser component. It doesn't have access to all the bells and whistles of HTML5 and might fail. I'm not sure if these will work on the device either although you would have a better chance there than in the simulator.

Unity WebGL External Assets

I'm developing some webGL project in Unity that has to load some external images from a directory, it runs all fine in the editor, however when I build it, it throws a Directory Not Found exception in web console. I am putting the images in Assets/StreamingAssets folder, that will become StreamingAssets folder in the built project (at root, same as index.html). Images are located there, yet browser still complains about not being able to find that directory. (I'm opening it on my own computer, no running web server)
I guess I'm missing something very obvious, but it seems like I could use some help, I've just started learning unity a week ago, and I'm not that great with C# or JavaScript (I'm trying to get better...) Is this somehow related to some javascript security issues?
Could someone please point me in the right direction, how I should be reading images(no writing need to be done) in Unity WebGL?
string appPath = Application.dataPath;
string[] filePaths = Directory.GetFiles(appPath, "*.jpg");
According to unity3d.com in webGL builds everything except threading and reflection is supported, so IO should be working - or so I thought:S
I was working around a bit and now I'm trying to load a text file containing the paths of the images (separated by ';'):
TextAsset ta = Resources.Load<TextAsset>("texManifest");
string[] lines = ta.text.Split(';');
Then I convert all lines to proper path, and add them to a list:
string temp = Application.streamingAssetsPath + "/textures/" + s;
filePaths.Add(temp);
Debug.Log tells me it looks like this:
file://////Downloads/FurnitureDresser/build/StreamingAssets/textures/79.jpg
So that seems to be allright except for all those slashes (That looks a bit odd to me)
And finally create the texture:
WWW www = new WWW("file://" + filePaths[i]);
yield return www;
Texture2D new_texture = new Texture2D(120, 80);
www.LoadImageIntoTexture(new_texture);
And around this last part (unsure: webgl projects does not seem easily debuggable) it tells me: NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
Can someone please enlighten me what is happening? And most of all, what would be proper to solution to create a directory from where I can load images during runtime?
I realise this question is now a couple of years old, but, since this still appears to be commonly asked question, here is one solution (sorry, the code is C# but I am guessing the javascript implementation is similar). Basically you need to use UnityWebRequest and Coroutines to access a file from the StreamingAssets folder.
1) Create a new Loading scene (which does nothing but query the files; you could have it display some status text or a progress bar to let the user knows what is happening).
2) Add a script called Loader to the Main Camera in the Loading scene.
3) In the Loader script, add a variable to indicate whether the asset has been read successfully:
private bool isAssetRead;
4) In the Start() method of the Loading script:
void Start ()
{
// if webGL, this will be something like "http://..."
string assetPath = Application.streamingAssetsPath;
bool isWebGl = assetPath.Contains("://") ||
assetPath.Contains(":///");
try
{
if (isWebGl)
{
StartCoroutine(
SendRequest(
Path.Combine(
assetPath, "myAsset")));
}
else // desktop app
{
// do whatever you need is app is not WebGL
}
}
catch
{
// handle failure
}
}
5) In the Update() method of the Loading script:
void Update ()
{
// check to see if asset has been successfully read yet
if (isAssetRead)
{
// once asset is successfully read,
// load the next screen (e.g. main menu or gameplay)
SceneManager.LoadScene("NextScene");
}
// need to consider what happens if
// asset fails to be read for some reason
}
6) In the SendRequest() method of the Loading script:
private IEnumerator SendRequest(string url)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
// handle failure
}
else
{
try
{
// entire file is returned via downloadHandler
//string fileContents = request.downloadHandler.text;
// or
//byte[] fileContents = request.downloadHandler.data;
// do whatever you need to do with the file contents
if (loadAsset(fileContents))
isAssetRead = true;
}
catch (Exception x)
{
// handle failure
}
}
}
}
Put your image in the Resources folder and use Resources.Load to open the file and use it.
For example:
Texture2D texture = Resources.Load("images/Texture") as Texture2D;
if (texture != null)
{
GetComponent<Renderer>().material.mainTexture = texture;
}
The directory listing and file APIs are not available in webgl builds.
Basically no low level IO operations are supported.

Loading local files in a WebBrowser Control

Im trying to load local files in a WebBrowser on Windows Phone 7.1 but Im always getting exceptions or a blank page.
I tried with
Stream stream = Application.GetResourceStream(
new Uri("./Html/par/index.html",
UriKind.Relative)).Stream;
using (StreamReader reader = new StreamReader(stream))
{
// Navigate to HTML document string
this.webBrowser.NavigateToString(reader.ReadToEnd());
}
this is firing a blank page.
I set index.html and all files needed (css/js) as Content and IsScriptEnable to "true".
Do you have an idea how to solve this problem?
i think the path is incorrect.
do you have /Html/par directories in your project ? secondly is index.html set to content ?
try
var rs = Application.GetResourceStream(new Uri("myFile.html", UriKind.Relative));
using(StreamReader sr = new StreamReader(rs.Stream))
{
this.webBrowser.NavigateToString(sr.ReadToEnd());
}
this might help
http://phone7.wordpress.com/2010/08/08/loading-a-local-html-file-in-the-webbrowser-control/
this might help undertand differences between resource and content
http://invokeit.wordpress.com/2011/09/30/images-and-build-actio-settings-in-wp7/
this link details how to load the file and other linked files
http://transoceanic.blogspot.co.uk/2011/07/wp7-load-local-html-files-and-all.html

Load file after page is complete without redirecting

I am trying to do pretty much the same, as is for example on Sourceforge. After a user creates some data, I generate a file and I want it to be offered to him after a page load. However, I know almost nothing about javascript and simple copy-paste of
<script type="text/javascript">
var download_url = "http://downloads.sourceforge.net/sourceforge/itextsharp/itextsharp-4.1.2-dll.zip?use_mirror=dfn";
function downloadURL() {
if (download_url.length != 0 && !jQuery.browser.msie) {
window.location.href = download_url;
}
}
jQuery(window).load(downloadURL);
</script>
is not enough. It is important for the user to download the file, so how to do that?
A question related to the previous is - where to store the file i created? Once while using the asp.net development server and then on the real IIS server? And how should this address look? When I tried
setTimeout("window.location.href='file://localhost/C:/Downloads/file.pdf'", 2000);
I was getting nothing, with HTTP an error of unknown address.
See Haack's DownloadResult example. It explains (I think) exactly what you're truing to do. Except you would provide the timeout call with your download action url.
you're asking the user's browser to look for a file on their own computer... that you're trying to save there.
you could use something like:
window.location.href='http://www.yourServer.com/generatePDF.asp?whatever=whatever'
where http://www.yourServer.com/generatePDF.asp?whatever=whatever is what is generating the pdf file for the user
On the server, you have to set the content disposition in the response header to "Attachment" as described in these answers.
If you do that, the download will not affect the page that is currently displayed in the browser. So, if you initiate a request in Javascript that gets an attachment, the browser will leave the page alone, and the user will see a message box with the Open/Save/Cancel question.
You can create your own PdfResult which extends ActionResult like this:
public class PdfResult : ActionResult
{
public byte[] Content { get; set; }
public string FileName { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.AddHeader("content-disposition", "attachment; filename=" + this.FileName);
response.AddHeader("content-length", this.Content.Length.ToString());
response.ContentType = "application/pdf";
using (MemoryStream memoryStream = new MemoryStream(this.Content))
{
memoryStream.WriteTo(response.OutputStream);
}
response.End();
}
Then in your action you can simply return the file as follows:
public ActionResult Pdf(string param1...)
{
var content = GeneratePdf(); //etc
var fileName = AssignFileName();
return new PdfResult { Content = content, FileName = fileName + ".pdf" };
}
A couple of different things. First, since you are using MVC, create an action that actually generates the file and returns it as a FileResult. The file can be an actual file on the server, but it can also be generated dynamically -- say in a MemoryStream -- and the FileResult created from that. Set the content to application/octet-stream or the actual file type if it's not one that will render in the browser via a plugin. Second, don't generate the file in the action that renders the page, but rather call the action that generates the FileResult from that page using the technique you've referenced (though it looks like they are doing something different for IE). If the MIME type is not one that can be rendered it will be downloaded.
public ActionResult GenerateFile( string value, int other )
{
MemoryStream file = new MemoryStream();
...
return File( file, "application/octet-stream" );
}

Categories

Resources