I am new to safari extension development. I need to access browser cookies specific to a web site. I know that this is possible with in chrome extension development. How can do this with safari extension development.
Asked
Active
Viewed 5,930 times
5
-
3If there's a way to do this, Apple's not telling. – chulster Jan 10 '12 at 16:04
1 Answers
3
From an injected script you can send the cookies to the extension. So when building the extension you have global.html and injected.js.
injected.js:
var cookies = document.cookie;
safari.self.tab.dispatchMessage("setCookies",cookies);
global.html (without the HTML tags):
var cookies = null;
function getCookies(incMsg) {
cookies = incMsg.message;
alert('I received them :) \n\n'+cookies);
}
safari.application.addEventListener("message",getCookies,false);
The code above will send all the cookies to the extension each time you load a page. Then of course you still need to read out the cookies. I used something like the following function (in global.html):
function readCookie(name) {
if(cookies) {
var nameEQ = name + "=";
var ca = cookies.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
}
Good luck!

Luigi van der Pal
- 507
- 3
- 12
-
1Btw I found this on Safari Extensions Development Guide: http://developer.apple.com/library/safari/#documentation/Tools/Conceptual/SafariExtensionGuide/MessagesandProxies/MessagesandProxies.html – Luigi van der Pal Apr 19 '12 at 15:55
-
Thanks, that's helpful to know. I assume this technique will also fetch any document cookies from a toolbar extension (that loads HTML which includes elements and AJAX where response header of page elements downloaded and XmlHttpRequest may contain Set-Cookie for session cookie). Sadly it doesn't look like Safari allows sending a cookie header out with XmlHttpRequest for toolbar extensions though. – David Jul 20 '13 at 19:56
-
Depends from where you are doing this request. Of you do a XHR from the injected script it will only allow XHR on that domain (where the injected script resides). But if I remember correctly from the global.html you can send requests to any resource. Most definitely because I was building a bookmarker at the time, which had to send the current page HREF to an external server from any page. – Luigi van der Pal Jul 23 '13 at 09:12
-
the toolbar page HTML content and AJAX requests are all on the same "page". The page includes the JS file for the AJAX calls. The XHR/AJAX calls need to send along the page's session cookie to get a proper response. I didn't have to do any special handling on Chrome, it just knew to do so. Don't know what exactly needs to be done on Safari. I currently have no injected scripts and no background/global pages. Just toolbar page that references a bundled local JS file. – David Apr 09 '15 at 23:43