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.

5
  • $("#content_ifr").find("img").remove(); does it work ? Commented Nov 27, 2019 at 10:33
  • 2
    Are you checking that iframe is loading or not Commented Nov 27, 2019 at 10:34
  • Are you doing this in iframe onload event Commented Nov 27, 2019 at 10:35
  • I'm running it in the console after the whole page loads. Like I said it works sometimes and sometimes it does not. The iframe is an inline iframe as well. Commented Nov 27, 2019 at 10:35
  • Assuming the iframe is same-origin (meaning the same URL domain), the only reason for this behavior is timing. You probably need to check first if the element actually exists and if it has really loaded. Commented Nov 27, 2019 at 10:44

3 Answers 3

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]

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

Try This:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.