Using the Plugin API
It makes sense to build out a user interface that exercises the plugin's API before implementing screen orientation functionality. Essentially, we want to rig up a testing harness that allows us to test feature parity across platforms quickly.
The focus of this walkthrough is how to build a Napacitor plugin, not how to build a particular frontend framework application, so we'll keep the UI deliberately small — a single TypeScript module that any framework (or no framework at all) can drive.
Add the following to your app's entry point, e.g. src/main.ts:
import { ScreenOrientation } from './plugins/screen-orientation';
// Track the current orientation and update the UI when it changes.
let orientation = '';
ScreenOrientation.addListener('screenOrientationChange', res => {
orientation = res.type;
render();
});
ScreenOrientation.orientation().then(res => {
orientation = res.type;
render();
});
function render() {
// Swap the DOM depending on orientation; cosmetic details omitted.
document.body.className = orientation;
}
Now serve the web app and open the browser's Developer Tools:
npm run dev
You should see the following error:
Uncaught (in promise) ScreenOrientation does not have web implementation.
That error checks out; we haven't implemented code for any of the platforms yet. Keep the browser open. We will implement the web platform first, then the C# side that runs inside the MAUI host.
How is the plugin being used?
Tracking the screen orientation:
The orientation variable holds the value of the screen's orientation. It can be updated by calling render(). Since we don't know the current screen orientation when the code starts executing, it's defaulted to an empty string.
Listening for changes:
An event listener is established that updates orientation when screenOrientationChange is fired:
ScreenOrientation.addListener('screenOrientationChange', res => {
orientation = res.type;
render();
});
The listener handle returned by addListener has a remove() method; call it when the UI is torn down to stop receiving events. removeAllListeners() clears every listener registered for this plugin:
ScreenOrientation.removeAllListeners();
Reading the current orientation:
The current screen orientation is obtained when the UI loads:
ScreenOrientation.orientation().then(res => {
orientation = res.type;
render();
});
Run npm run build so the new UI is used when we run the app inside the MAUI host later.
We now have a user interface that exercises our plugin's API, so let's start implementing functionality! We will target the web first in our next step: the web implementation.