Afridi's fourth five-wicket haul in tests wrapped up Bangladesh's second innings for 157 on Day 4, setting Pakistan a 202-run target to win.
Openers Abid Ali and Abdullah Shafique then helped Pakistan reach 109-0 at stumps, leaving the team needing 93 more runs on the final day.
Ali, who scored 133 in the first innings, was on 56 and debutant Shafique was unbeaten on 53 when bad light ended play early for the fourth consecutive day.
Bangladesh had a 44-run first-innings lead after posting 330 and then bowling Pakistan out for 286.
“We just had a terrible last session yesterday which put us under a lot of pressure in the game,” Bangladesh coach Russell Domingo said.
“They (Pakistan) need another 93 runs, so it will need something really special. Anything is possible in test cricket. We have to come tomorrow morning believing we still have a chance. If we can pick up one or two wickets in the first half an hour, anything is possible.”
Ali and Shafique brought up their second consecutive century partnership in the match, frustrating Bangladesh bowlers for one-and-a-half sessions.
Ali completed his third half-century off 92 balls, flicking left-arm spinner Taijul Islam for three runs.
Shafique joined him in reaching his fifty in the next-to-last over, lofting offspinner Mehidy Hasan for the lone six of the innings, over deep mid-wicket.
“We planned to have a good start to the chase and we are successful,” Shafique said.
“We are now on course of a victory but we should still play well because the fifth day morning session could be tricky one.”
Earlier, Liton Das, who hit 114 in the first innings, battled with little assistance from his Bangladesh teammates in making 59 off 89 balls.
Debutant Yasir Ali scored 36 and appeared to steady Bangladesh's innings, combining with Liton for 47 runs.
But he had to leave the ground after being hit on his helmet by a short-pitch delivery from Afridi.
It ruined the momentum Bangladesh gained after beginning the fourth day on 39-4 and losing experienced batter Mushfiqur Rahim (16) in the first over when he offered no shot against fast bowler Hasan Ali (2-52).
After Yasir retired, Sajid Khan trapped Hasan (11) lbw with a delivery that spun sharply.
Yasir's concussion substitute, Nurul Hasan, then played a rash shot to be dismissed for 15.
Liton, meanwhile, played confidently to bring up his 10th half-century off 83 balls, guiding Afridi's delivery to backward point for a single.
But he didn't stay long as Afridi had him lbw with an inswinger and then dismissed Abu Jayed with a short ball.
Sajid Khan, who finished with a career-best 3-33, had Taijul stumped to bring an end to the Bangladesh's innings as the hosts lost their last three wickets in six balls for no runs.