JavaScript Cookie Creation Issue - java

I am currently trying to create a cookie in JavaScript. The idea is that when the user clicks the extension icon whilst watching a YouTube video it gets the tab name and saves it as a cookie. This is so that I can then access the cookie from my Java program.
I am using chrome and I can't see the cookie in the list when I have pressed it even though the alert successfully displays so I am wondering if anyone can see an issue with my code.
Also if anyone has a better idea of how to get the tab name to my Java program I would be happy to hear your ideas.
Thanks everyone, here's my code:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
createCookie(cookieName, cookieValue);
});
}
function createCookie(name, value)
{
var expires = new Date().getTime() + (1000 * 3600);
var domain = ";domain=.youtube.com";
document.cookie = name + "=" + value + ";expires=" + expires + domain + ";path=/";
alert(name + " = " + value + ". Date = " + expires);
}
EDIT: I have changed my code to use the chrome API's provided by Google, great success!

If anyone has the same problem I have used the Google API's for chrome concerning cookies.
My new code is the following:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
}
Note: In the manifest file you will need permissions for tabs, cookies and the website domain. Furthermore I have not stated when the cookie expires thus it expires when the session is closed.

Related

Why do I get OAuthProblemException error='invalid_request' description='Handle could not be extracted' when doing Exact OAuth

When doing calls to Exact-on-line API to get authenticated we run into the problem that getting the first refresh-token fails. We're not sure why. This is what we get back from Exact:
Http code: 400
JSON Data:
{
error='invalid_request',
description='Handle could not be extracted',
uri='null',
state='null',
scope='null',
redirectUri='null',
responseStatus=400,
parameters={}
}
We use this Java code based on library org.apache.oltu.oauth2.client (1.0.2):
OAuthClientRequest oAuthRequest = OAuthClientRequest //
.tokenLocation(BASE_URL + "/api/oauth2/token") //
.setGrantType(GrantType.AUTHORIZATION_CODE) //
.setClientId(clientId) //
.setClientSecret(clientSecret) //
.setRedirectURI(REDIRECT_URI) //
.setCode(code) //
.buildBodyMessage();
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse oauthResponse = client.accessToken(oAuthRequest, OAuth.HttpMethod.POST);
We did do the first step (getting the 'code' as used in setCode(...)) using a localhost-redirect as displayed in https://support.exactonline.com/community/s/knowledge-base#All-All-DNO-Content-gettingstarted There we copy the code from the address-bar of our browser and store it in a place the next computer-step can read it again.
This is due to the fact that the code was copied from your browsers address-bar. There you will find a URL-encoded version of the code (visible in the '%21' often) which when passed into the setCode verbatim will fail the subsequent calls.
Suggestion: URL-decode the value or setup a small temporary localhost-HTTP-server using Undertow or the like to catch the code that was send to you localhost-URL:
Undertow server = Undertow.builder() //
.addHttpListener(7891, "localhost") //
.setHandler(new HttpHandler() {
#Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
String code = exchange.getQueryParameters().get("code").getFirst();
LOG.info("Recieved code: {}.", code);
LOG.info("Store code");
storeCode(code);
LOG.info("Code stored");
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send( //
"Thanks for getting me the code: " + code + "\n" //
+ "Will store it for you and get the first refreshToken..." //
+ "Please have a look at " + OAUTH_STATE_INI
+ " for the new code & refreshToken in a minute" //
);
done.add("done");
}
}).build();
server.start();
NB: Do make sure the redirect URL is correct in your Exact-app-settings

Play change Language dynamallicy

Fairly new to Play trying to change the language dynamically.
route
GET /language/:lang controllers.Index.setLanguage(lang: String)
Tried so far (but none of them work)
Lang.apply(language);
Lang.change(language); // <-- doesn't even compile
Lang.apply(language);
ctx().changeLang(language);
view
#import play.i18n.Messages
...
#Messages.get("message")
#messages.at("message")
...
Both not working..
application.config
messages
Method with some logging
public Result setLanguage(String language) {
Http.Context context = Http.Context.current();
String langFromHttpContext = context.lang().language();
String langFromCtx = ctx().lang().language();
String playLangCookieVal = request().cookies().get("PLAY_LANG").value();
boolean changed = ctx().changeLang(language);
Logger.info("Request param: " + language);
Logger.info("Http context language: " + langFromHttpContext);
Logger.info("ctx language: " + langFromHttpContext);
Logger.info("PLAY_LANG cookie value: " + langFromCtx);
Logger.info("Changed: " + changed);
return ok(index.render("Index"));
}
Result
application - Request param: en
application - Http context language: nl
application - ctx language: nl
application - PLAY_LANG cookie value: nl
application - Changed: false
You need to delete the application.langs="nl" from the configuration. It's deprecated and replaced by the play.i18n.langs.
You must leave only play.i18n.langs=["en","nl"]
You code does not work because Play reads the application.langs="nl" and ignore play.i18n.langs=["en","nl"] (because langs already read from the application.langs), so it suggest your application use only "nl" language and, of course could not set it to "en", so ctx().changeLang(language) method return false
Try this:
ctx().changeLang(language);

Selenium cookie with another domain

I have a code on selenium to test a form. But first i go to another page and then redirect to the my page. When i set cookies to new domain , i got error :
Exception in thread "main" org.openqa.selenium.InvalidCookieDomainException: You may only set cookies for the current domain
My Code :
//it is going to example.com and example redirect me to the "example.com" all cookie domains is "example.com"
driver.get("http://www.example.com?id=1");
Set<Cookie> cookies = driver.manage().getCookies();
Iterator<Cookie> itr = cookies.iterator();
while (itr.hasNext()){
Cookie c = itr.next();
System.out.println("Cookie Name: " + c.getName() + " --- " + "Cookie Domain: " + c.getDomain() + " --- " + "Cookie Value: " + c.getValue());
driver.manage().addCookie(c);
}
How can i manage that ? I have to get/set cookies for example.com
Like mentioned in previous answer this is expected behavior.
The only work around to date is to driver.get("domain.com/404") page. But this doesn't always work due to SSO often protects domain.com/*
I have made a new feature request on the spec: https://github.com/w3c/webdriver/issues/1238
to make it so the 404 work-around can always work.
The webdriver spec
https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie forces
the current browser session to be on the domain where you are adding
the cookie to.
This makes tons of sense and I agree with it.
This unfortunately prevents 2 key use cases:
You want to re-use cookies from another webdriver session in a new
session to avoid repeating the work it took to get the cookies. Such
as having to repeat a login. Allow a webdriver pool to be shared
amongst unrelated threads where each thread might have their own
cookies. The only current work around is to attempt to force the
webdriver to go to a 404 error page with something like:
webdriver.get("http://the-cookie-domain.com/404adsfasdf"). This would
cause the page to go to domain and would allow you to add cookies with
addCookie. But this hardly ever works. Because the page is very often
protected by SSO, any attempt to go to http://the-cookie-domain.com/*
sends you to an SSO login page e.g. http://login.ssodomain.com and now
you have the same problem.
We should add a new method to the spec webdriver.goTo404Page(domain)
to allow this use-case. This method should simulate a 404 HTTP status
code response from domain in the browser.
Alternatively maybe be a new overload to addCookie could allow this,
for example: void addCookie(Cookie var1, String goTo404PageOfDomain);
By allowing users to go to a fake 404 page of any given domain, this
guarantees the 404-page workaround works for any page and these 2 use
cases are now possible.
For firefox, you can modify Marionette slightly to just remove this check.
diff --git a/testing/marionette/cookie.js b/testing/marionette/cookie.js
--- a/testing/marionette/cookie.js
+++ b/testing/marionette/cookie.js
## -144,14 +144,14 ## cookie.add = function(newCookie, {restri
newCookie.domain = "." + newCookie.domain;
}
- if (restrictToHost) {
- if (!restrictToHost.endsWith(newCookie.domain) &&
- ("." + restrictToHost) !== newCookie.domain &&
- restrictToHost !== newCookie.domain) {
- throw new InvalidCookieDomainError(`Cookies may only be set ` +
- `for the current domain (${restrictToHost})`);
- }
- }
+// if (restrictToHost) {
+// if (!restrictToHost.endsWith(newCookie.domain) &&
+// ("." + restrictToHost) !== newCookie.domain &&
+// restrictToHost !== newCookie.domain) {
+// throw new InvalidCookieDomainError(`Cookies may only be set ` +
+// `for the current domain (${restrictToHost})`);
+// }
+// }
// remove port from domain, if present.
// unfortunately this catches IPv6 addresses by mistake
diff --git a/testing/marionette/driver.js b/testing/marionette/driver.js
--- a/testing/marionette/driver.js
+++ b/testing/marionette/driver.js
## -2638,9 +2638,9 ## GeckoDriver.prototype.addCookie = functi
let {protocol, hostname} = this.currentURL;
const networkSchemes = ["ftp:", "http:", "https:"];
- if (!networkSchemes.includes(protocol)) {
- throw new InvalidCookieDomainError("Document is cookie-averse");
- }
+// if (!networkSchemes.includes(protocol)) {
+// throw new InvalidCookieDomainError("Document is cookie-averse");
+// }
let newCookie = cookie.fromJSON(cmd.parameters.cookie);
diff --git a/testing/marionette/test_cookie.js b/testing/marionette/test_cookie.js
--- a/testing/marionette/test_cookie.js
+++ b/testing/marionette/test_cookie.js
## -190,10 +190,10 ## add_test(function test_add() {
});
equal(2, cookie.manager.cookies.length);
- Assert.throws(() => {
- let biscuit = {name: "name3", value: "value3", domain: "domain3"};
- cookie.add(biscuit, {restrictToHost: "other domain"});
- }, /Cookies may only be set for the current domain/);
+// Assert.throws(() => {
+// let biscuit = {name: "name3", value: "value3", domain: "domain3"};
+// cookie.add(biscuit, {restrictToHost: "other domain"});
+// }, /Cookies may only be set for the current domain/);
cookie.add({
name: "name4",
Why not let the browser be redirected to "example.com" before adding the cookies. Once on that domain, add the cookie values you've taken from "example.com" and the refresh the page?
As per the answer by the team on this issue on the project tracker,
The cookies methods only act on cookies that would be visible as this
is the only thing that can be made to work consistently across all
browsers. The behaviour that you see is the expected behaviour.

gwt Cookies not setting or getting

Environment
Eclipse Juno Service Release 1
GWT 2.5
Google Chrome with the GWT developer plugin
Running GWT on the Jetty server using 'run application' as Google web application
I am trying to set 2 cookies using gwt using the following code:
if(result.getStatus() == ServerResponse.SUCCESS) {
System.out.println("I will now set cookies: " + result.getMessage() + " and " + Integer.toString(result.getValue().getId()));
Cookies.setCookie("opsession", result.getMessage(), new Date(System.currentTimeMillis() + ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES));
Cookies.setCookie("opuser", Integer.toString(result.getValue().getId()), new Date(System.currentTimeMillis() + ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES));
System.out.println("Cookie set: session: " + Cookies.getCookie("opsession"));
main.checkLoginAndRedirect();
System.out.println("Redirected.");
} else if(result.getStatus() == ServerResponse.FAILURE){
new MessageBox(result.getShortTitle(), result.getMessage()).show();
}
It doesn't seem to work. The println's are there for debugging, and here is the output:
I will now set cookies: 1er1qmaly9ker and 1
Cookie set: session: null
nullnull
Redirected.
ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES is (was an int) a long that returns 20.
Update
Using
if(Cookies.getCookie("opsession") == null) {
System.out.println("opsession: cookie not found at all.");
}
I've confirmed that the cookie is not placed at all, and does not have a 'null' String value.
I've also changed
ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES into a long.
Update
Fiddler confirms that cookie data has been sent:
Response sent 30 bytes of Cookie data: Set-Cookie: JSESSIONID=4kr11hs48gvq;Path=/
But only if I use the longer version of setCookie:
Cookies.setCookie("opuser", Integer.toString(result.getValue().getId()), new Date(System.currentTimeMillis() + ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES), null, "/", false);
If I use the String, String, long variant, fiddler notices no cookie data.
Should be
new Date(System.currentTimeMillis()
+ (ClientUser.SESSION_EXPIRY_TIME_IN_MINUTES * 60000)))
to convert the expiry time to milliseconds.

DJ Native Swing javascript command problems

Using DJ Native Swing it is possible to show a web page within a java application. When you do this it is also possible to communicate from the browser to the java runtime environment using the "command" protocol. The documentation has a code snippet which demonstrates it's usage:
function sendCommand( command ){
var s = 'command://' + encodeURIComponent( command );
for( var i = 1; i < arguments.length; s+= '&' + encodeURIComponent( arguments[i++] ) );
window.location = s;
}
As it looks here it seems to be a regular GET request to an url using the command protocol instead of http. Although when I create and image, script tag or just and ajax get request there is no response and the breakpoint in the java runtime isn't triggered.
I don't want to set the window.location because I don't want to navigate away from the page I am currently at. Using the link to navigate to a command url does work though but it also navigates away from the current page. The page uses OpenLayers and dojo. (I have also tried dojo.io.script)
After some work I have found a neat way to communicate with the java runtime which doesn't trigger a refresh of the page every time there is communication. It is inspired on the way JSONP works to get around the cross domain restriction in most browsers these days. Because an iFrame will also trigger a command:// url it possible to do a JSONP like action using this technique. The code on the client side (browser):
dojo.provide( "nmpo.io.java" );
dojo.require( "dojo.io.script" );
nmpo.io.java = dojo.delegate( dojo.io.script, {
attach: function(/*String*/id, /*String*/url, /*Document?*/frameDocument){
// summary:
// creates a new tag pointing to the specified URL and
// adds it to the document.
// description:
// Attaches the script element to the DOM. Use this method if you
// just want to attach a script to the DOM and do not care when or
// if it loads.
var frame = dojo.create( "iframe", {
id: id,
frameborder: 0,
framespacing: 0
}, dojo.body( ) );
dojo.style( frame, { display: "none" } );
dojo.attr( frame, { src: url } );
return frame;
},
_makeScriptDeferred: function(/*Object*/args){
//summary:
// sets up a Deferred object for an IO request.
var dfd = dojo._ioSetArgs(args, this._deferredCancel, this._deferredOk, this._deferredError);
var ioArgs = dfd.ioArgs;
ioArgs.id = dojo._scopeName + "IoScript" + (this._counter++);
ioArgs.canDelete = false;
//Special setup for jsonp case
ioArgs.jsonp = args.callbackParamName || args.jsonp;
if(ioArgs.jsonp){
//Add the jsonp parameter.
ioArgs.query = ioArgs.query || "";
if(ioArgs.query.length > 0){
ioArgs.query += "&";
}
ioArgs.query += ioArgs.jsonp
+ "="
+ (args.frameDoc ? "parent." : "")
+ "nmpo.io.java.jsonp_" + ioArgs.id + "._jsonpCallback";
ioArgs.frameDoc = args.frameDoc;
//Setup the Deferred to have the jsonp callback.
ioArgs.canDelete = true;
dfd._jsonpCallback = this._jsonpCallback;
this["jsonp_" + ioArgs.id] = dfd;
}
return dfd; // dojo.Deferred
}
});
When a request is sent to the java runtime a callback argument will be supplied and a webBrowser.executeJavascript( callbackName + "(" + json + ");" ); action can be executed to trigger the callback in the browser.
Usage example client:
dojo.require( "nmpo.io.java" );
nmpo.io.java.get({
// For some reason the first paramater (the one after the '?') is never in the
// paramater array in the java runtime. As a work around we stick in a dummy.
url: "command://sum?_",
callbackParamName: "callback",
content: {
numbers: [ 1, 2, 3, 4, 5 ].join( "," )
},
load: function( result ){
console.log( "A result was returned, the sum was [ " + result.result + " ]" );
}
});
Usage example java:
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
#Override
public void commandReceived(WebBrowserCommandEvent e) {
// Check if you have the right command here, left out for the example
// Parse the paramaters into a Hashtable or something, also left out for the example
int sum = 0;
for( String number : arguments.get( "numbers" ).split( "," ) ){
sum += Integer.parseInt( number );
}
// Execute the javascript callback like would happen with a regular JSONP call.
webBrowser.executeJavascript( arguments.get( "callback" ) + "({ result: " + sum + " });" );
}
});
Also with IE in the frame I can highly recommend using firebug lite, the dev tools for IE are not available.

Categories