MyNick
MyNick

Reputation: 556

Chrome extrension - chrome.tabs.executeScript doesnt run with file

I'm trying to run code when some press my icon in my chrome extension. When i used to run the code with code: "code..." it changed the title but didn't run the jquery code. I read that you need to execute it from a file so i added a file. Now both of them doesn't work, before the title was changed (when i used code) and now (when i use the file) it doesn't work. I added alerts to see what code run, none of them work, not even the first

I got the following app:

manifest.json:

{
    "name": "Pandora Likes",
    "version": "0.0.1",
    "manifest_version": 2,
    "background": { "scripts": ["background.js"] },
    "browser_action": {
        "default_icon": {
            "19": "icons/19x19.png"
        },
        "default_title": "Pandora Likes"
    },
    "permissions": ["tabs","http://*/","https://*/"]
}

background.js:

function onClick() {
chrome.tabs.query({},function(array_of_Tabs) {
    for(var i=0;i<array_of_Tabs.length; i++){
        if(array_of_Tabs[i].url.indexOf('pandora.com')> -1) {
            //chrome.tabs.update(array_of_Tabs[i].id, { selected: true });
            chrome.tabs.executeScript(array_of_Tabs[i].id,{file: "like.js"});
        }

    }
});
}

chrome.browserAction.onClicked.addListener(onClick);

like.js:

alert("before");
document.title='gaga';
alert('after');
console.log("before);
$('.thumbDownButton').click();
console.log("after);

Thank you for your help

Upvotes: 0

Views: 143

Answers (1)

Xan
Xan

Reputation: 77482

Lots of problems here.

  1. Your match patterns (http://*/) only match URLs with blank paths. I.e. you would match http://example.com/ but not http://example.com/test/.

    You can fix that with a single match pattern *://*/* (matches http or https) or even <all_urls>. Or, since you're only looking for Pandora, *://*.pandora.com/*.

  2. Your like.js has a syntax error, made obvious by the syntax highlighting here on SO. You forgot a closing " on lines 4 and 6.

  3. To use $ in your context script, you need to include jQuery first even if it's present on the page, since context scripts are isolated from the page. (Chrome has a console-only version of $, but it is also unavailable to content scripts)

  4. Even if you do include jQuery, triggering click() might not lead to what you expect. Again, since the content script is isolated, the click handler lives in the page context and may* not be triggered by your code. Consider injecting code into the page.

Please note: you should spend some effort debugging your extension yourself. Chrome is usually helpful with its error messages; see background's page console via a link at chrome://extensions/, and content script's errors will appear in the tab's console.


* May not be triggered, because you can still create a DOM mouse click event to trigger the page's listeners, but I'm reasonably sure .click() will not do that.

Upvotes: 1

Related Questions