Existing web-based security applications have failed in many situations due to the great intelligence of attackers. Among web applications, Cross-Site Scripting (XSS) is one of the dangerous assaults experienced while modifying an organization's or user's information. To avoid these security challenges, this article proposes a novel, all-encompassing combination of machine learning (NB, SVM, k-NN) and deep learning (RNN, CNN, LSTM) frameworks for detecting and defending against XSS attacks with high accuracy and efficiency. Based on the representation, a novel idea for merging stacking ensemble with web applications, termed “hybrid stacking”, is proposed. In order to implement the aforementioned methods, four distinct datasets, each of which contains both safe and unsafe content, are considered. The hybrid detection method can adaptively identify the attacks from the URL, and the defense mechanism inherits the advantages of URL encoding with dictionary-based mapping to improve prediction accuracy, accelerate the training process, and effectively remove the unsafe JScript/JavaScript keywords from the URL. The simulation results show that the proposed hybrid model is more efficient than the existing detection methods. It produces more than 99.5% accurate XSS attack classification results (accuracy, precision, recall, f1_score, and Receiver Operating Characteristic (ROC)) and is highly resistant to XSS attacks. In order to ensure the security of the server's information, the proposed hybrid approach is demonstrated in a real-time environment.