문제

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.

다른 팁

I wrote a wrapper to make this almost transparent. The script injection solution also doesn't let you get any return values from the functions, while this proxy does.

Include this in your content script and call methods on GroovesharkProxy instead of window.Grooveshark.

https://github.com/msfeldstein/Grooveshark-Chrome-Extension-Proxy

http://www.macromeez.com/use-groovesharks-js-api-from-a-chrome-extension/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top