Add theme integrated sidebar example (#308)

This commit is contained in:
Tim Nguyen
2017-11-07 22:29:07 +00:00
committed by wbamberg
parent 3e2d1833d7
commit b5242f8748
4 changed files with 97 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
# Theme integrated sidebar
## What it does
An example using the theme API to integrate the interface of a sidebar_action to the current theme properties.
## What it shows
How to use the browser.theme.getCurrent(), browser.theme.onUpdated and the sidebar_action API.
## Instructions to try this
- Install a WebExtension theme that sets `accentcolor`, `toolbar` or `toolbar_text`
- Install this extension
- The sidebar should then use colors from the WebExtension theme

View File

@@ -0,0 +1,20 @@
{
"description": "A sidebar that integrates with the current theme",
"homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/theme-integrated-sidebar",
"manifest_version": 2,
"name": "Theme integrated sidebar",
"permissions": [
"theme"
],
"sidebar_action": {
"default_title": "Theme integrated sidebar",
"default_panel": "sidebar.html"
},
"version": "1.0",
"applications": {
"gecko": {
"id": "theme-integrated-sidebar@mozilla.org",
"strict_min_version": "58.0a1"
}
}
}

View File

@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>My theme-integrated sidebar</title>
<style>
#myElement {
font: menu;
font-size: 1.5em;
font-weight: 500;
padding: 1em;
margin: 1em;
}
</style>
</head>
<body>
<div id="myElement">This is an awesome themed element!</div>
<script src="sidebar.js"></script>
</body>
</html>

View File

@@ -0,0 +1,43 @@
function setSidebarStyle(theme) {
const myElement = document.getElementById("myElement");
// colors.frame and colors.accentcolor are aliases
if (theme.colors && (theme.colors.accentcolor || theme.colors.frame)) {
document.body.style.backgroundColor =
theme.colors.accentcolor || theme.colors.frame;
} else {
document.body.style.backgroundColor = "white";
}
if (theme.colors && theme.colors.toolbar) {
myElement.style.backgroundColor = theme.colors.toolbar;
} else {
myElement.style.backgroundColor = "#ebebeb";
}
if (theme.colors && theme.colors.toolbar_text) {
myElement.style.color = theme.colors.toolbar_text;
} else {
myElement.style.color = "black";
}
}
// Set the element style when the extension page loads
async function setInitialStyle() {
const theme = await browser.theme.getCurrent();
setSidebarStyle(theme);
}
setInitialStyle();
// Watch for theme updates
browser.theme.onUpdated.addListener(async ({ theme, windowId }) => {
const sidebarWindow = await browser.windows.getCurrent();
/*
Only update theme if it applies to the window the sidebar is in.
If a windowId is passed during an update, it means that the theme is applied to that specific window.
Otherwise, the theme is applied globally to all windows.
*/
if (!windowId || windowId == sidebarWindow.id) {
setSidebarStyle(theme);
}
});