Conversion of table to Excel from JavaScript - javascript

I need to export my EditorGridPanel grid data to excel without sending any data to server-side, cross browser and cross platform solution that will work in ie6 and ie7. Any pure JavaScript solution is good as well!
So far i have found only data URI solution which is great but ie supports it only from 8-th version. Also there is a possibility to export through ActiveX component but it is not what i want since it makes my app depended to Windows and MSOffice.
Can you recommend me any solution ?

You could export to csv and then import that file into Excel , Open Office or Numbers?

Well after a wile of thinking i understood that this question is stupid because due to sandbox policy of js there is no possibility to export it directly from js.
As i said earlier i found some partial ways to do that:
ActiveX export and Data URI scheme

Here is a solution with a server-side call, but no server-side code writting.
http://code.google.com/p/gwt-table-to-excel/

The class below do that without server side.
public class TableToExcel {
public static final <T> void save(final CellTable<T> table, String filename) {
final AnchorElement a = Document.get().createAnchorElement();
a.setHref("data:application/vnd.ms-excel;base64," + base64(table.getElement().getString()));
a.setPropertyString("download", (filename.endsWith(".xls") || filename.endsWith(".xlsx")) ? filename : filename + ".xls");
Document.get().getBody().appendChild(a);
Scheduler.get().scheduleEntry(new ScheduledCommand() {
#Override
public void execute() {
click(a);
a.removeFromParent();
}
});
}
private static native void click(Element elem) /*-{
elem.click();
}-*/;
public static native String base64(String data) /*-{
return btoa(data);
}-*/;
}

Related

Why can't I access localStorage in a string variable on android studio?

I have a pretty basic code for a webview app:
package com.budget.noname.budget;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String data = "<p id='v'></p><script>x=3; y=5; m=0; document.getElementById('v').innerHTML = m;</script>";
WebView simpleWebView=(WebView) findViewById(R.id.simpleWebView);
WebSettings webSettings = simpleWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setDomStorageEnabled(true);
//simpleWebView.loadUrl("file:///android_asset/index.htm");
simpleWebView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", "");
}
}
If I put my webapp (index.htm) in the assets folder and load it, it works perfectly, but my code is available for anyone who cares to extract the .apk.
I was trying to paste the code on a String and the load it with loadDataWithBaseURL. It worked almost as well. The thing is: if I try to access the localStorage, the code breaks. Why is that?
Example:
String data = "<script>x=localStorage.getItem('name');</script>";
Doesn't work!!! Although, as I said, if I load the same code from the assets folder, it works.
Just like already stated here before:
The access to localStorage is only allowed on pages from certain
"Web-safe" schemes, like http:, https: and file:. It doesn't work for
about: and data: schemes for example, or for any custom scheme you
might be using.
If you take a look at the loadDataWithBaseURL()'s docs, we can see the following statement to baseUrl param:
String: the URL to use as the page's base URL. If null defaults to
'about:blank'.
This explains why only your file:/// example works, and also means that you'll have to pass something valid to this param. You can load whatever URL you want, like:
webView.loadDataWithBaseURL("http://google.com", data, "text/html", "UTF-8", "");
Or even http://localhost:80 will get it working.
However, this won't make your localStorage values available for other instances of WebView (they do not conversate on Android, by default). A common option is using another library that abstracts it for you, like AndroidLocalStorage, e.g.

Avoid caching JS, CSS files page after each deployment

We are using ASP.Net. But in the front end, we are using HTML pages. So server side code could not used there.
By implementing like this "login.js?s09809808098" we can resolve this. But we can't manually edit this on every pages before each deployment. Is there any method to edit the html pages in server side when a page is requested. Or any other method to resolve this issue?
You can try adding expiration headers and dont cache headers to fix this problem.
You can also create a center repo for static URL assests and when your repo return the URL append a software version like login.js?v1 this way you will get new version with every release. also define the version number as a property in the repo class.
public static class URLRepo {
public string AppVersion = "1";
public string GetURL (enumURLName urls)
{
switch(enumURLName)
{
case enumURLName.LoginJS
return "Login.JS?v" + AppVersion;
break;
}
}
}
public enum enumURLName
{
LoginJS,
LoginCSS
}

Android Web-View : Inject local Javascript file to Remote Webpage

It has been asked many times before, I browsed through everything, no clear answers yet.
Question simplified: Is it possible to inject local Javascript file (from asset or storage) to remote webpage loaded in an Android Web-View? I know that it is possible to inject such files to local Webpages (Assets HTML) loaded in a Web-View.
Why do I need this to work? : To make browsing experience faster, by avoiding downloading of bigger files such as Js and CSS files every time. I want to avoid Web-View Caching.
There is a way to 'force' the injection of your local Javascript files from local assets (e.g., assets/js/script.js), and to circumvent the 'Not allowed to load local resource : file:///android_assets/js/script.js ...' issue.
It is similar to what described in another thread (Android webview, loading javascript file in assets folder), with additional BASE64 encoding/decoding for representing your Javascript file as a printable string.
I am using an Android 4.4.2, API level 19 Virtual Device.
Here are some code snippets:
[assets/js/script.js]:
'use strict';
function test() {
// ... do something
}
// more Javascript
[MainActivity.java]:
...
WebView myWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
injectScriptFile(view, "js/script.js"); // see below ...
// test if the script was loaded
view.loadUrl("javascript:setTimeout(test(), 500)");
}
private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
try {
input = getAssets().open(scriptFile);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
myWebView.loadUrl("http://www.example.com");
...
loadUrl will work only in old version use evaluateJavascript
webview.evaluateJavascript("(function() { document.getElementsByName('username')[0].value='USERNAME';document.getElementsByName('password')[0].value='PASSWORD'; "+
"return { var1: \"variable1\", var2: \"variable2\" }; })();", new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d("LogName", s); // Prints: {"var1":"variable1","var2":"variable2"}
}
});
Yes, you could use shouldInterceptRequest() to intercept remote url loading and return local stored content.
WebView webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient() {
#Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
if (url.equals("script_url_to_load_local")) {
return new WebResourceResponse("text/javascript", "UTF-8", new FileInputStream("local_url")));
} else {
return super.shouldInterceptRequest(view, url);
}
}
});
Be careful using evaluateJavascript: if there is a syntax error or exception thrown in your javascript it will call your onReceiveValue with a null. The most common way to support both SDK 19 as well as lower seems to be like this:Fill form in WebView with Javascript
Also if you get terribly desperate for some kind of browser functionality (in my case, never could figure out how to get DRM to work well) you could use a bookmarklet within normal chrome, which works only if you type the bookmark name into the omnibox but does work and does inject javascript.
Also be aware that with the default WebView you can't use javascript alerts to test anything, they don't show. Also be aware that "video" by default (like html <video> tags) doesn't "really work" by default and also DRM video doesn't work by default, they're all configure options :\

How to consume JavaScript classes generated by WSDL utility?

I generated classes in JavaScript from a WSDL by using Visual Studio's WSDL utility.
wsdl /o:SomeClasses.js /l:js https://SomeCompany.com/SomeService?WSDL
The output contains classes (in JavaScript) that look like this:
public System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1") System.SerializableAttribute() System.Diagnostics.DebuggerStepThroughAttribute() System.ComponentModel.DesignerCategoryAttribute("code") System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:some.company")
class SomeUser {
private var domainNameField : System.String;
private var userNameField : System.String;
///<remarks/>
public final function get domainName() : System.String {
return this.domainNameField;
}
public final function set domainName(value : System.String) {
this.domainNameField = value;
}
///<remarks/>
public final function get userName() : System.String {
return this.userNameField;
}
public final function set userName(value : System.String) {
this.userNameField = value;
}
}
Is it possible to write OOP JavaScript utilizing these classes? If so, what is the syntax, examples, etc.
When you specify the JS language for the Web Services Description Language Tool, you are NOT specifying JavaScript, but JScript. It's not even JScript that InternetExplorer can fully understand, it's JScript.NET.
JScript.NET is a server side scripting language based on JScript but with added features - available only on the server side - like the class you've got in the code you posted.
You should look for other ways of generating JavaScript code, maybe with a tool like Wsdl2js or performing your WS call with JQuery. You can't use the Wsdl.exe generated code inside InternetExplorer as InternetExplorer only supports the old JScript language (and non IE browsers don't even support that).

How to add different Javascript in development and production wicket

I have a wicket application in which I have added the javascript files within the markup html:
<script src="script/jquery.min.js" type="text/javascript"></script>
My javascript files are not placed beside my .java or .html files, they are in different location in the server as can be seen on previous script declaration.
My question is: Is it possible to add these javascript files depending on the application mode? I.E. if the application is in development mode, load one javascript file, if it is in production load this other one.
Thanks!
PS: the idea is to load "min" version on production but the extended files on development so debugging becomes posible
NOTE: Watching different answers here I re-state: the problem is not finding when the wicket app is in development or deployment mode, I know that, but is about how to change html markup or adding different JavaScript resources
extendig the answer of #rotsch you can do it in wicket 1.5 with :
#Override
public void renderHead(IHeaderResponse response) {
if(DEVELOPMENT)
response.renderString("<script type=\"text/javascript\" src=\"url1\"></script>");
else
response.renderString("<script type=\"text/javascript\" src=\"url2\"></script>");
}
https://cwiki.apache.org/WICKET/migration-to-wicket-15.html#MigrationtoWicket1.5-RemovedHeaderContributorandfriends.
You can find out in which mode you are with the following code:
RuntimeConfigurationType.DEPLOYMENT.equals(getApplication().getConfigurationType())
or
RuntimeConfigurationType.DEVELOPMENT.equals(getApplication().getConfigurationType())
I use this directory layout:
resources
|---JQueryResource.java
|---jquery-1.6.4.js
|---jquery-1.6.4.min.js
With this class:
public class JQueryResource {
/**
* Must be called in a RequestCycle.
*
* #return Url for the jQuery library.
*/
public static String getURL() {
if (Application.get().usesDevelopmentConfig()) {
Url url =
RequestCycle.get().mapUrlFor(
new PackageResourceReference(JQueryResource.class, "jquery-1.6.4.js"),
null);
return url.toString();
} else {
Url url =
RequestCycle.get().mapUrlFor(
new PackageResourceReference(JQueryResource.class,
"jquery-1.6.4.min.js"), null);
return url.toString();
}
}
}
This is how I add the resource to my page.
#Override
public void renderHead(IHeaderResponse a_response) {
a_response.renderJavaScriptReference(JQueryResource.getURL());
}
You could use pack:tag to compress all your resources: http://sourceforge.net/projects/packtag/
In your web.xml/.properties file you can specify whether to pack it or not depending on your production mode.
I set a property in a properties file with I add to the path when starting the VM.
Then I do a if else similar to the PHP answer.

Categories

Resources