England reached 415-9 declared, a first-innings advantage of 264 thanks to wicketkeeper Foakes’ maiden domestic century and skipper Stokes’ first century as a player.
By the end of the match, South Africa had fought its way up to 23-0, although down by 241.
After Anrich Nortje dismissed Jonny Bairstow and Zak Crawley, England was at 147-5 and four runs behind when Stokes and Foakes joined forces.
With one game remaining, England is poised to tie the series at 1-1, thanks to their sixth-wicket partnership of 173.
Both men reversed the lbw rulings, dropping Stokes on 92 before succumbing for 103.
When England declared, South Africa had nine overs to stay alive in the rays of the setting sun with Foakes still standing at 113.
Although the Proteas’ openers, Dean Elgar and Sarel Erwee, succeeded, it will be a difficult challenge even to force this match into a fourth day.