0

I'm attempting to remove an image from an embedded iframe (inline iframe). While it works sometimes, sometimes it failes with an error. I am running this code on Chrome. This behaviour is strange. I have tried this on a few sites and I am unable to find any reason for this.

I would like to know why it fails sometimes and does not sometimes with all parameters the same (I'm simply executing this in the console). Secondly, if possible is there an alternative solution?

$("#content_ifr").contents().find("img").remove();

Error message that occurs sometimes:

Uncaught TypeError: Cannot read property 'contents' of null

If it helps, I'm attempting to remove images and extra content from the WordPress page editor (Classic) using JavaScript.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Winston Jude
  • 569
  • 2
  • 11

3 Answers3

1

Being that you said it sometimes works and sometimes it doesn't. When it works, check the Javascript context. I was running into issues where my code worked with DevTools opened, but if I refreshed the page, the javascript context would revert to "Top", and I needed to be in that frame.

[Javascript context[1]

Jason Owens
  • 525
  • 2
  • 6
  • 21
1

Turns out that my Chrome extension was interfering with this. We were attempting to run this script using a Chrome extension on a WordPress site.

Changing these lines to this worked:

jQuery("#content_ifr").contents().find("img").remove();

As @Jason Owens pointed out, the context was for some reason switching. I noticed that using 'jQuery' instead of $ seemed to work. I think this was because the Chrome extension was using standard jQuery as a dependency. However, '$' didn't work WordPress avoids the '$' symbol using noConflict and uses 'jQuery' instead.

Winston Jude
  • 569
  • 2
  • 11
0

We can't remove elements from Iframe but we can hide

Try This:

$(document).ready(function(){
    $('#content_ifr').contents().find('img').hide();
});
Prasad
  • 1
  • 3