Allah, The Glorious is everywhere and He knows everything that happens everywhere on the earth and the whole universe. He gifts His most humble servants (Muhammad and his 12 successors) whatever He wants from His Knowledge whenever and wherever He wants. They know whatever Allah informs them.
The Hadeeth Qudsi says:Allah says: O my servant, obey me, you will like me عبدي أطعني تكن مثلي.
Wassalam.