I believe the basis for the claim stems from the Bavli (Niddah 13a):
רב יהודה ושמואל הוו קיימי אאיגרא דבי כנישתא דשף ויתיב בנהרדעא אמר ליה רב יהודה לשמואל צריך אני להשתין א"ל שיננא אחוז באמתך והשתן לחוץ. היכי עביד הכי והתניא...? אמר אביי עשאו כבולשת... כיון דבעיתי לא אתי להרהורי. והכא מאי ביעתותא איכא... ואב"א ביעתותא דשכינה ואיבעית אימא אימתא דמריה עליה דקרי שמואל עליה אין זה ילוד אשה
Rav Yehuda and Shmuel were standing on the roof of the synagogue that was destroyed and rebuilt in Neharde’a. Rav Yehuda said to Shmuel: What can I do? I need to urinate. Shmuel said to him: Shinnana, hold your penis, so that the water does not fall onto the synagogue roof, and urinate outward, away from the synagogue.
The Gemara asks: How could Rav Yehuda do so? But isn’t it taught in a baraita... Abaye says: The Sages rendered the halakhic status of this situation like that of a troop of marauders... Here too, in this incident involving Rav Yehuda, since he is afraid he will not come to have sexual thoughts.
The Gemara asks: And what fear is there here, in the case of Rav Yehuda?... And if you wish, say that the awe of the Divine Presence that dwells in the synagogue is upon Rav Yehuda. And if you wish, say that the awe of his Master, God, is upon him...
From here we can infer when the Torah scroll is open/read -and ordinarily in a synagogue which adds to the assumption that the divine presence is present- we are not suspect of hirhurim (AKA yetzer ha’ra).
(While being used to explain the halachic permissibility of a woman’s qualification for being one of the seven ‘olim (since the reading of the Torah is being done in a shul; Meg. 23a), other various halachic applications were made with the above forming the basis, most notable -perhaps- was the Chida (Marit Ayin, op cit.). R. Shlomo Kluger (Tuv Taam Vadaat §189), citing a midrash, writes that the evil inclination is not in control in a synagogue.)