In an availability group it is possible to select whether a backup should be performed on a primary or secondary replica.
This script creates a list of databases that are in an availability group and reside on the primary replica. Because these are candidates for a backup the script will be run. When no candidates are present the script will not run.
Simply execute the script with an SQL Server Agent job at the required intervals.