Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an HTML dialog pop-up in chrome extension

I'm working on a Chrome extension that will pop up a dialog box in the center of the screen when the user hits a keyboard shortcut. It will then use JavaScript to asynchronously load in content from the MediaWiki API. But I'm having difficulty figuring out how to create and display a dialog with JavaScript. I don't want to use the Chrome html-popup browser action, because it appears off in the corner of the screen.

I know how to use JavaScript to display an existing HTML dialog box, as this answer explains, but I don't know how to insert one into the DOM. I don't want to use JavaScript's alert function, since that opens a separate window. So is there a way to create and display an HTML modal dialog when an event triggers a JavaScript function in a chrome extension?

like image 871
Jonathan Cox Avatar asked Aug 20 '15 08:08

Jonathan Cox


People also ask

How do I add a border radius to Chrome extension?

There is one to make the popup. html border-radius that to add another Div container to popup HTML, set the body background to none and give the background color to the div container. After that, you can give the radius to the container.


1 Answers

You should be able to use the javascript for the answer you linked to open that dialog whenever you want by injecting your javascript via a content script. Google has documentation for this here: https://developer.chrome.com/extensions/content_scripts

Basically, a content script runs on whatever pages you tell it to. So you could tell it to run on all web pages (configured via the manifest). This content script would add your listener, and then append your dialog to the body tage (or wherever, body is usually safe).

The code would look something like:

$(document).on( 'keypress', 'body', function( e ){
    var code = e.keyCode || e.which;

    if( code = /*whatever, key shortcut listener*/ ) {
        document.body.innerHTML += '<dialog>This is a dialog.<br><button>Close</button></dialog>';
        var dialog = document.querySelector("dialog")
        dialog.querySelector("button").addEventListener("click", function() {
            dialog.close()
        })
        dialog.showModal()
    }
});

You may want to add safety code to check for your body tag; it's on normal pages but specialty pages may error (such as chrome://*).

As long as this runs on your content script, and your content script runs on your desired pages, you can run whatever listeners/dom changers you want this way.

like image 154
Brian Avatar answered Oct 17 '22 21:10

Brian