How to not add to history entry within iFrame

Problem: So I have a iFrame page within my main page. Whenever I interact within the iFrame within the main page, im assuming its adding on more entrees to the history because whenever I click back “to go back to the last main page” I have to click it multiple times (2-3 times).

Solution: I just need to not log the entires when within the iFrame. So when I click the back button it will go back to the last main page and not within the iFrame.

Heres my current code

export function showPage(newUrl: string): void {
  const page1 = document.getElementById('showpage');

  page1.setAttribute('src', `${page1Href}#${newUrl}`);


  page.style.display = 'block';
}

What I think I need to do is this solution:

var frame = $('#myIFrame')[0];  
frame.contentWindow.location.replace(newUrl);

but when I do this, it just throws a Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'contentWindow') which is because the frame is null. How do I fix this?

And this solution also might cause a CORS/security risk as well. So im not sure of the best solution here either. I have tried a few things to just replace the history but I cant get it to work. Any help would be greatly appreciated.