I'm making a chrome extension (with link submission feature) for my Django-powered site. I'm using django-tastypie to post links from JavaScript. However, I can't figure out how to access django sessions from JavaScript in order to determine the submitter of the link. Using console.log(document.cookie)
doesn't sound like the possibility as document.cookie obviously accesses the cookie from the current page, not the cookie from my django-powered website. Any help would be appreciated.

- 1,074
- 3
- 20
- 40
-
2This is why you need OAuth. Have the user login via OAuth to access the API, and then you get an OAuth token that you can pass back and forth to know which user you're working with. – Chris Pratt Jul 24 '12 at 19:52
-
Chris, can you please elaborate on this? This http://django-tastypie.readthedocs.org/en/latest/authentication_authorization.html#oauthauthentication is essentially talking about protecting my APIs by requiring authentication. I have no clue how get the logged-in user info from JavaScript from tastypie? – Arman Jul 25 '12 at 03:35
-
Sorry. Seems tastypie's built-in OAuth only has consumption support, i.e. it will verify that the token is valid, but doesn't actually communicate with the OAuth service. For more functionality, you'll need to either implement your own OAuth server with something like django-oauth, or pick from 3rd-party OAuth providers like Google, Twitter, etc. Each provider has its own mechanisms for retrieving user info from a authenticated OAuth session. – Chris Pratt Jul 25 '12 at 14:45
-
i think best answer is [here](https://stackoverflow.com/a/34720262/7337499) thanks to @Stefano – Ebrahim Karimi Jul 14 '17 at 19:46
1 Answers
There are two ways to do this as far as I can tell.
Implement oAuth on your Django app server side, and use a Javascript oAuth method to authenticate your users. This is probably alot of work for you if you don't already provide oAuth, so is probably a bad idea.
Use an iframe with a page from your site. Inject a content script into the iframe and pull data from it. You might have to set up a specific endpoint.
In your manifest using a match pattern:
{
...,
"content_scripts": [
{
"matches": ["http://yoursite.com/api/extension"],
"js": ["content_script.js"],
"all_frames": true
}
],
...
}
The endpoint, loaded into an iframe by another content script, might look something like this:
...
<div id="user_info">joe_user</div>
...
Then your script would pull the textContent
of the #user_info div and send it to the background page for your use:
var elem = document.querySelector('#user_info');
chrome.extension.sendMessage({
text: elem.textContent
});
For more on messaging, see Google's Message Passing documentation.
I think that should work for you if all you need is user information. I wouldn't send any sensitive information like this though.

- 2,415
- 1
- 21
- 22