Skip to content

Instantly share code, notes, and snippets.

@showsky
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save showsky/af9e309a4daf152061dc to your computer and use it in GitHub Desktop.

Select an option

Save showsky/af9e309a4daf152061dc to your computer and use it in GitHub Desktop.
Java embed javascript code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
/*
requirement lib: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Download_Rhino
ref: https://vec.io/posts/embed-javascript-in-android-java-code-with-rhino
*/
public class Demo {
public static String getHTML(String urlString) {
HttpURLConnection conn;
BufferedReader rd;
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
public static Object[] convertJSParams(String... params) {
Object[] obj = params;
return obj;
}
public static String runJavascript(String tag, String sourceCode, String functionName, Object[] functionParams) {
String result = null;
Context rhino = Context.enter();
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
rhino.evaluateString(scope, sourceCode, tag, 1, null);
Function function = (Function) scope.get(functionName, scope);
Object obj = function.call(rhino, scope, scope, functionParams);
result = Context.toString(obj);
} finally {
Context.exit();
}
return result;
}
public static void main(String[] args) {
String TAG = "main";
String youtubeLiveURL = "https://www.youtube.com/watch?v=s5Vj3VKOZGc";
String html = getHTML(youtubeLiveURL);
//String escape = html.replace("\"", "'");
String jsCode = "function test(a, b) {return a * b;}";
String jsCode2 =
"function getLiveUrl(data) {" +
"var h = data.indexOf('hlsvp') + 8," +
"e = data.indexOf('m3u8') + 4;" +
"return data.slice(h, e);}";
String result = runJavascript(TAG, jsCode2, "getLiveUrl", convertJSParams(html));
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment