简体   繁体   中英

How to call Javascript function from an inserted HTML element in a Chrome extension?

I created a chrome extension that inserts some html into a page (see screenshot below of how it looks...top right corner is the inserted HTML).

在此处输入图片说明

I want to create functionality such that when the user clicks the "Skip for now" text, the inserted HTML should disappear or be hidden. I'm having a difficult time doing that within my current code.

Inject.js gets called through this function:

chrome.tabs.executeScript(tab.ib, {
    file: 'inject.js'
});

Inject.js (I'm not sure how to write a new function to hide all the elements that were created below and how to call that function from the HTML section at the bottom):

(function() {


        // Create div
        var div = document.createElement('div');

        // Div styling

            // Positioning
            div.style.position = 'fixed';
            div.style.boxSizing = 'border-box';
            div.style.display = 'block';
            div.style.zIndex = 10000000;
            div.style.top = '20px';
            div.style.right = '20px';

            // Size
            div.style.height = '130px';
            div.style.width = '330px';

            // Padding
            div.style.paddingTop = '20px';
            div.style.paddingBottom = '20px';
            div.style.paddingLeft = '20px';
            div.style.paddingRight = '20px';
            div.style.borderRadius = '25px';

            // Text
            div.style.textAlign = 'center';
            div.style.fontSize = '11px';

            // Color
            div.style.backgroundColor = '#505F69';
            div.style.color = 'white';
            div.style.border = '2px solid grey';


        // HTML
        div.innerHTML += '<u><a href = "http://example.com" style="color:white;font-size:15px;">Click to activate your To a Cause donation.</a></u><br><br>';
        div.innerHTML += '<u><a href="#" style="color:white;">Skip for now</u></a>';

        // Append
        document.body.appendChild(div);


})();

You should create the skip button as an HTML node (like you did for the div) and append it to the div. Then you can do:

skipButton.onclick = () => {
    document.body.removeChild(div);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM