Last active
November 25, 2017 13:01
-
-
Save cypressious/2e6a9d92268e9fa0ef686624aee1d7cb to your computer and use it in GitHub Desktop.
Kotlin Firefox Extension popup.kt part 2 https://medium.com/@Cypressious/your-second-firefox-extension-in-kotlin-bafd91d87c41
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun listenForClicks() { | |
document.addEventListener("click", { e -> | |
val target = e.target as? Element ?: return@addEventListener | |
browser.tabs.query(Query(active = true, currentWindow = true)) | |
.then({ tabs -> handleClick(target, tabs[0].id) }) | |
.catch(::reportError) | |
}) | |
} | |
fun handleClick(target: Element, id: Int) { | |
if (target.classList.contains("beast")) { | |
val url = getUrl(target.textContent) | |
browser.tabs.insertCSS(id, CssDetails(CSS_HIDE_PAGE)) | |
browser.tabs.sendMessage(id, jsObject { | |
command = "beastify" | |
beastURL = url | |
}) | |
} else { | |
browser.tabs.removeCSS(id, CssDetails(CSS_HIDE_PAGE)) | |
browser.tabs.sendMessage(id, jsObject { | |
command = "reset" | |
}) | |
} | |
} | |
fun getUrl(name: String?): String { | |
val relative = "beasts/${name?.toLowerCase()}.jpg" | |
return browser.extension.getURL(relative) | |
} | |
const val CSS_HIDE_PAGE = """ | |
body > :not(.beastify-image) { | |
display: none; | |
} | |
""" | |
inline fun jsObject(init: dynamic.() -> Unit): dynamic { | |
val o = js("{}") | |
init(o) | |
return o | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment