doforumda
doforumda

Reputation: 174

How to add a <div> tag to currently opened page using Chrome extension?

I want to add div tag to the currently open website when user clicks chrome extension Icon. This image should appear on the left top corner of the page. How can I achieve this goal?

The code below adds div tag to extension window.

<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">

        $(function() {
            $("#click").click(function(){
                chrome.tabs.getSelected(null, function(tab){
                    var tabUrl = tab.url;
                    //alert(tabUrl);
                    document.querySelector('div#content').style.display = 'block';
                });
                //chrome.tabs.executeScript(null, {code: "document.body." + setAttribute("class",img)});
            });
        });
    </script>
</head>
<body>
    <div id="content"></div>
    <div id="click">Click Here</div>
</body>
</html>

Upvotes: 0

Views: 3514

Answers (2)

Reyraa
Reyraa

Reputation: 4294

appending elements into DOM is fulfilled by content scripts, those scripts run after page load event. as you can see in the chrome extension documentations, so they won't affect already opened tabs.

Upvotes: 1

Boris Smus
Boris Smus

Reputation: 8472

Presumably by icon you mean browserAction, the button on the right of the omnibox. Bind to the chrome.browserAction.onClicked event, and run executeScript on the current tab, injecting a script that adds a position: absolute; top: 0; left: 0; image to the DOM of the page.

Here's a good sample to get you started (changes the page color on clicking the browser action)

Upvotes: 1

Related Questions