How can I display a modal dialog from the context menu?
I can show a new window from context menu which opens in its own tab:
var menuItem = {
\"id\"
I have done the same. Just use content script
to show modal
.
Example : When user clicks the context menu item, send message to content script to let it know about it so that it should open a modal.
background.js:
chrome.contextMenus.onClicked.addListener(function (clickData) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: "openModal"});
});
});
contentscript.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
switch (request.type){
case "openModal":
$('#myModal').modal({
backdrop: 'static',
keyboard: false
});
break;
});
Make sure to include necessary css and js files under content_scripts
in manifest.json
"content_scripts": [
{
"matches": ["https://*/*"],
"css":["bootstrap.min.css"],
"js":["jquery.min.js","bootstrap.min.js","contentscript.js"],
"run_at":"document_end"
}
]
NOTE : Using bootstrap.min.css
may conflict with the page UI and it may change it. To avoid this, move your modal and the required js and css files in a separate html file(modal.html
). Then inject your iframe
into the tab using content script.
var iframe = document.createElement('iframe');
iframe.src = chrome.extension.getURL("modal.html");
iframe.frameBorder = 0;
iframe.id = "myFrame";
$(iframe).hide();//necessary otherwise frame will be visible
$(iframe).appendTo("body");
Remember to add modal.html
and all the css and js files that are used inside modal.html
like modal.js
,bootstrap.min.js
,bootstrap.min.css
under web_accessible_resources
:
web_accessible_resources": ["modal.html","modal.js","bootstrap.min.js","bootstrap.min.css"]
Now you can hide or show your iframe
using content script but to show and hide modal, it can be done from inside iframe
only. So you would need to pass a message from background
to iframe
to show the modal.The code above mentioned for contentscript will work for iframe
also.
In case you want to hide the iframe, just send message from iframe
to contentscipt
using window.parent.postMessage()
.
Example:
modal.js:
window.parent.postMessage({ type: "hideFrame" }, "*");
contentscript.js:
window.addEventListener("message", function(event) {
if (event.data.type == "hideFrame") {
$("#myFrame").hide();
}
});