A planned suicide attack on the Grand Mosque in the Muslim holy city of Mecca was foiled, according to Saudi security forces, who say they cornered the would-be bomber in an apartment where he blew himself up.

In a statement on state television, the Saudi Arabian interior ministry said three cells had planned an attack on worshipers during the holy month of Ramadan.

Once trapped in the apartment, the would-be attacker exchanged fire with police before detonating explosives.

The blast caused the building to collapse, injuring six foreigners and five members of the security forces.

The final ten days of Ramadan are considered the most holy time of year for Muslims, with millions of worshipers descending on Mecca, the birthplace of the Prophet Mohammad.

It was not immediately clear who was behind the plot to attack the mosque, although ISIL has in the past carried out attacks in Saudi Arabia.

Five suspected militants were arrested during the operation.