Marià
Marià

Reputation: 263

Chrome extension that clicks a button

I have a page with a button and I'm creating a chrome extension to click on it but it doesn't work:

<input type="submit" name="commit" value="add to basket" class="button"/>

This is my manifest.json

{
    "description": "Click",
    "manifest_version": 2,
    "name": "click-product-addtocart-button",
    "version": "0.1",

    "permissions": [
        "activeTab"
    ],

    "background": {
        "scripts": [
            "background.js"
        ]
    },

    "browser_action": {
        "default_icon": {
            "32": "/images/icons/16.png"
        },
        "default_title": "Click product"
    }
}

and this is my background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, {
        code: "document.getElementByName('commit')[0].click();"
    });
});

I click on the app but nothing happens. I have tried several things but that seems not to work

Upvotes: 1

Views: 414

Answers (1)

Ben Botvinick
Ben Botvinick

Reputation: 3345

Your manifest must request permission to access the current page by URL as well as just the current tab. Update your permissions to the following:

"permissions": [
     "activeTab",
     "*://*/*"
],

This will allow the extension to access any page. I would also recommend changing name to id. This will prevent any confusion in the future. You would do this as follows:

<input type="submit" id="commit" value="add to basket" class="button">

Then for background.js:

chrome.browserAction.onClicked.addListener(function() {
    chrome.tabs.executeScript({
        code: "document.getElementById('commit').click();"
    });
});

You'll notice I also removed the specificity of the tab that you had in your question. This is not necessary.

Upvotes: 2

Related Questions