As the Internet of Things (IoT) expands rapidly and 5G networks become more widespread, the need for strong cybersecurity measures in IoT systems has become increasingly critical. Traditional security methods are no longer sufficient due to the shear volume, diversity, and limited processing capabilities of IoT devices. The high data transmission speeds of 5G networks further intensify the potential risks, making it essential to implement effective security measures. One of the major threats to IoT systems is Cross-Site Scripting (XSS) attacks. To address this issue, we introduce a new machine learning (ML) approach designed to detect and predict XSS attacks on IoT systems operating over 5G networks. By using ML classifiers, particularly the Random Forest classifier, our approach achieves a high classification accuracy of 99.89% in identifying XSS attacks. This research enhances IoT security by addressing the emerging challenges posed by 5G networks and XSS attacks, ensuring the safe operation of IoT devices within the 5G ecosystem through early detection and prevention of vulnerabilities.