开发者

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

开发者 https://www.devze.com 2023-04-06 11:08 出处:网络
I want to add div tag to the currently open website when user clicks chrome extensi开发者_JAVA技巧on Icon. This image should appear on the left top corner of the page. How can I achieve this goal?

I want to add div tag to the currently open website when user clicks chrome extensi开发者_JAVA技巧on 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>


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号