d9120
d9120

Reputation: 511

Adding HTML to a page with a Chrome Extension

Okay Here's what I want my extension to do. I want it to add some HTML to a page (Label, button whatever).

Here's What I have...

content.js (it actually tries to add a label not a button)

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.action == "addButton") {
        addButtonHTML();
    }
});


function addButtonHTML() {
    $('body').append("<label>HHHHHHHHHHHHHHHHHHHHH</label>");

}

background.js

addButton("addButton");

function addButton(action) {
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, {
            action: action,
            tabid: tab.id
        }, function(response) {});
    });
}

My question is, what am I doing wrong? and what should my manifest look like this is what I have as of now.

manifest.json

{
    "name": "Extension",
    "version": "1.0",
    "description": "Does Stuff",
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "page_action": {
        "default_icon": "icon-19.png"
    },
    "permissions": [
        "http://*/*",
        "https://*/*",
        "tabs"
    ],
    "icons": {
        "48": "icon-48.png",
        "128": "icon-128.png"
    },
    "content_scripts": [{
        "matches": ["http://*/*", "https://*/*"],
        "js": ["content.js"]
    }],
    "manifest_version": 2
}

Thank you

Upvotes: 0

Views: 454

Answers (1)

Teepeemm
Teepeemm

Reputation: 4508

You indicated that you only want this on certain pages which you determine in background.js. This means you can remove the content script from your manifest, and I think you will also be able to change the tabs permission to activeTab. There is still the question of whether the label should always be loaded on these pages, or only after a user action.

If the label should always be there, you want background.js (which will run on every page load) to call chrome.tabs.executeScript to load content.js (reference), which no longer needs the listener that you added.

If the label should appear as the result of a user action, this sounds like you want a page action. In addition to the above, background.js should call chrome.pageAction.show(tabId) to show the page action icon, and use chrome.pageAction.onClicked.addListener(loadScriptFunction) to call executeScript.


Edit: I think I was able to finally diagnose where your attempt went wrong. Google doesn't specify when background.js executes, but it seems to be rarely (extension startup?), and definitely not after content.js. If you wrap your bare addButton("addButton") inside of a chrome.pageAction.onClicked.addListener, then it appears to work.

Upvotes: 1

Related Questions