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.
Related
I am trying to use html2canvas on a Shopify product page to convert a div to an imgURL to set as a form value. Whenever I use html2canvas, I get the error:
Uncaught ReferenceError: onLoadStylesheet is not defined at HTMLLinkElement.onload
When I try to pinpoint the error, it just directs me to <!doctype html> highlighted with the message
Each dictionary in the list "icons" should contain a non-empty UTF8 string field "type".
This also prevents the form from posting for some reason.
html2canvas(document.querySelector("#container"), {useCORS: true, logging: false}).then(canvas => {
document.getElementById("imgURL").value = canvas.toDataURL();
});
How do I fix this?
I found the solution, if you are using ScriptTags and loading JavaScript from your own domain then you will get the error, solution is to use the cache=true when creating the ScriptTag and this will load JavaScript from Shopify's CDN and html2canvas works
Here is the code snippet in C# to create a script tag with caching:
dynamic scriptTagBody = new ExpandoObject();
scriptTagBody.script_tag = new ShopifyScriptTag()
{
Event = "onload",
Src = "https://example.com/script.js",
DisplayScope = "all",
Cache = true
};
HttpContent content = new JsonContent(scriptTagBody);
content.Headers.Add("X-Shopify-Access-Token", "MyAccessToken");
string url = "https://yourshop.myshopify.com/admin/api/2021-04/script_tags.json";
await _httpClient.PostAsync(url, content);
ShopifyScriptTag in the above snippet is a simple POJO with those properties
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.
Good morning!
I have been working on a client side browser based app using JavaScript that (all of a sudden) needs the capability to save and load files locally.
The saved files are plain text (.txt) files.
I have managed to get JavaScript to read existing text files. However, I am unable to find reliable information on how to create and edit the contents of these files.
Based on what I see online, I am under the impression that you can't do this with JavaScript alone.
I found out from another source that the best way to do this is outsource the file writing/editing to a Java file and let Java do the work.
I found a code snippet and tweaked it around a bit, but it is not working and I seem to be at a loss:
JAVASCRIPT
<!Doctype html>
<html>
<OBJECT ID="Test" height=0 width=0
CLASSID="CLSID:18F79884-E141-49E4-AB97-99FF47F71C9E" CODEBASE="JavaApplication2/src/TestJava.java" VIEWASTEXT>
</OBJECT>
<script language="Javascript">
var Installed;
Installed = false;
try
{
if (Test==null)
Installed = false;
else
Installed = true;
}
catch (e)
{
Installed = false;
}
alert ("Installed :- " + Installed);
TestStr = Test.SendStr("Basil");
alert (TestStr);
</script>
</html>
JAVA
import javax.swing.*;
public class TestJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public String SendStr(String lStr)
{
return lStr + "!!!";
}
}
If someone could point me in the right direction or even just explain why this isn't working, I would appreciate it.
I believe the sandbox issue prevents all browsers from performing any and all local file writing, without an enormous amount of working around the access restrictions. It is easier to write files remotely on the server than to write them locally to the client. This is true across all browsers.
So while it may be possible to perform the load function, you cannot perform the 'save' function on the local machine.
Hi I am very new to java script in android? My problem is my files not loaded in the android assets.
When i run my code i got exception like.
07-08 11:49:10.809: I/chromium(25627): [INFO:CONSOLE(1)] "Uncaught ReferenceError: myFunction is not defined", source: (1)
07-08 11:49:11.100: I/chromium(25627): [INFO:CONSOLE(78)] "Uncaught TypeError: Cannot call method 'getContext' of null", source: file:///android_asset/keyGasGraphBuilder.js (78)
But In my code i have added all the files in the assets.
and also i have added my code.js file in the html page while loading
<script type="text/javascript" src="file:///android_asset/code.js"></script>
and from the code i have call like
duvaltriangle.getSettings().setJavaScriptEnabled(true);
WebSettings setting =duvaltriangle.getSettings();
duvaltriangle.loadUrl("file:///android_asset/Dynamic Ratings - Duval DEMO.htm");
String name = "Duval 2b OLTC Type IIb";
duvaltriangle.loadUrl("javascript:myFunction(\""+name+"\")");
My js file:
Please tell me where i missed. I think i have done all the procedure right way.
function myFunction(name)
{
document.getElementById("demo").innerHTML = name;
}
Use:
duvaltriangle.loadUrl("file:///android_asset/Dynamic Ratings - Duval DEMO.htm");
duvaltriangle.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
String name = "Duval 2b OLTC Type IIb";
duvaltriangle.loadUrl("javascript:myFunction(\""+name+"\")");
}
});
Because it takes time to load url. So, scripts must be loaded when page finishes loading.
Warning recieved : WebKit discarded an uncaught exception in the webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame: delegate: The view passed in does not have a window.
dropbox plugin method for getting the files from dropbox inside it i have created an array to get the files and send it to javascript to display the output
getfiles:-
jscallback=[NSString stringWithFormat:#"getFilename(%#)",dropBoxArray];
[self writeJavascript:jscallback];
Method defined in javascript
window.getFilename=function(str)
{
alert(str);
cordova.exec(linkDropboxCB, linkDropboxFail,"DropboxPlugin","getfiles", [""]);
}
getfiles is the method in the dropbox plugin,which contains the above code.
Please help me to remove the warning.