I want to make a chrome extension that will connect to a localhost server to receive instructions to play songs in Grooveshark using the Grooveshark Javascript API. (http://grooveshark.com/GroovesharkAPI.html)
For example, if I type window.Grooveshark.addSongsByID([13963],true)
in the javascript console, it'll add the song and start playing like it should I need to be able to do this from the extension. So to start, I just wanted to make an extension with a background page and just this single script to execute the command:
background.html
<!doctype html>
<html>
<head>
<script src="background.js"></script>
</head>
<body>
</body>
</html>
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(
null, {code:"window.Grooveshark.addSongsByID([13963],true)"});
});
manifest.json
{
"name": "Play song in Grooveshark",
"version": "0.1.0",
"background_page": "background.html",
"permissions": [
"tabs", "http://*/*"
],
"browser_action": {
"name": "Play song",
"default_icon": "icon.png"
}
}
Could anyone tell me why it doesn't work?
Thank you very much!!
Content scripts cannot access parent page's window
object. You would need to inject <script>
tag into a page with your code.
//bg page
chrome.tabs.executeScript(null, {
code: "injectJs('window.Grooveshark.addSongsByID([13963],true)')"
});
//content script
function injectJs(code) {
var scr = document.createElement("script");
scr.type = "text/javascript";
scr.text = code;
(document.head || document.body || document.documentElement).appendChild(scr);
}
You can inject injectJs
function through manifest to all pages, and then call it when needed.