Skip to content Skip to sidebar Skip to footer

Jquery Dialog Not Displaying Correctly When Injected

I'm making a Chrome extension and I'm trying to inject Jquery when the user clicks an element on the page. When I try to create a dialog via Jquery by doing: var box = document.cre

Solution 1:

The only way to completely isolate your styles from the page is using Shadow DOM (which was shipped by Chrome in 2013). You can also use the Dialog element, so Jquery is not even needed.

let shadow
try {
 shadow = document.body.attachShadow({ mode: "open" })
 shadow.appendChild(document.createElement("slot"))
} catch(error) {
 shadow = document.body.createShadowRoot()
 shadow.appendChild(document.createElement("content"))
}
let dialog = document.createElement("dialog")
dialog.innerHTML = `
 Test Dialog<br><br>
 <button>Close</button>
`
shadow.appendChild(dialog)
dialog.querySelector("button").addEventListener("click", function() {
 dialog.remove()
})
dialog.showModal() //or show()

References:

https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOMhttps://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialoghttps://developers.google.com/web/fundamentals/getting-started/primers/shadowdomhttps://developers.google.com/web/updates/2013/09/dialog-element-Modals-made-easy

Solution 2:

If you're going to inject any code into a page, you'll have to contend with whatever code is already there. For example, when you inject your own jQuery without taking certain additional steps, you're clobbering the page's existing jQuery (assuming it has one). Doing this could break page functionality.

There currently isn't a way to completely isolate your CSS from the page CSS. The best you can do is create a likely unique id for your dialog's outermost element and alter your injected CSS so that all the rules are prefixed to match this id. You may also need some special reset rules for that id to override whatever the page has going on.

Post a Comment for "Jquery Dialog Not Displaying Correctly When Injected"