gutenberg icon indicating copy to clipboard operation
gutenberg copied to clipboard

Custom styles/scripts are not loaded inside the preview iframe

Open NenadObradovic opened this issue 4 years ago • 27 comments

Description

Hello guys,

Is there any issue with styles/scripts loading inside iframe (responsive editor)?

I enqueued 3 scripts with default function and that scripts are loaded fine initial but when I clicked on the tablet or mobile preview button, some scripts disappeared/did not load inside the head tag.

Please check the attachment and screenshots inside.

Thanks for your time.

Best regards, Nenad Obradovic

Step-by-step reproduction instructions

I also tested with the default Twenty Twenty-One theme, I just enqueued Google Font link and I got the same issue

/**
 * Enqueue block editor script.
 *
 * @since Twenty Twenty-One 1.0
 *
 * @return void
 */
function twentytwentyone_block_editor_script() {
	wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css?family=DM+Sans%3A400%2C500%2C600%2C700&subset=latin-ext&display=swap&ver=1.0.0' );
	wp_enqueue_script( 'twentytwentyone-editor', get_theme_file_uri( '/assets/js/editor.js' ), array( 'wp-blocks', 'wp-dom' ), wp_get_theme()->get( 'Version' ), true );
}

add_action( 'enqueue_block_editor_assets', 'twentytwentyone_block_editor_script' );

Screenshots, screen recording, code snippet

https://imgur.com/a/SPIPNvZ

Environment info

  • WordPress 5.9
  • Chrome
  • Window 11

Please confirm that you have searched existing issues in the repo.

Yes

Please confirm that you have tested with all plugins deactivated except Gutenberg.

Yes

NenadObradovic avatar Feb 09 '22 16:02 NenadObradovic

Hello again,

Unfortunately, you messed a lot of things with the new iframe editor preview, conditional you set are "crazy" and work only for your cases otherwise you blocked or removed any custom/external/3rd party scripts.

In this file src/components/iframe/index.js you made function styleSheetsCompat and that function has 2 problems:

  1. If we include any external CSS file that file will not be loaded because of this case
try {
	// May fail for external styles.
	// eslint-disable-next-line no-unused-expressions
	styleSheet.cssRules;
} catch ( e ) {
	return;
}

External files on Chrome browser will be blocked and cssRules result will be "Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules at CSSStyleSheet" - https://stackoverflow.com/questions/48753691/cannot-access-cssrules-from-local-css-file-in-chrome-64/49160760#49160760

  1. The Second problem is 3rd party styles or theme custom styles. In the same file -> same function -> you can find this piece of code
const isMatch = Array.from( cssRules ).find(
	( { selectorText } ) =>
		selectorText &&
		( selectorText.includes( `.${ BODY_CLASS_NAME }` ) ||
			selectorText.includes( `.${ BLOCK_PREFIX }` ) )
);

where

const BODY_CLASS_NAME = 'editor-styles-wrapper';
const BLOCK_PREFIX = 'wp-block';

If we have for example 3rd party style - Swiper.css you will block it because inside that file there is no editor-styles-wrapper or wp-block classes as selector https://www.screencast.com/t/YxASDqA97u0 and that file will not be executed/loaded.

The same issue is with any custom theme or plugin styles that don't contain these classes. In my case, I have several CSS files which don't contain these classes and all files are blocked.

Could you please consider changing this logic or adding some hooks/JS variables so we can be able to extend/change or add our items?

Best regards, Nenad Obradovic

NenadObradovic avatar Feb 11 '22 11:02 NenadObradovic

Help us move this issue forward. This issue is being marked stale since it has no activity after 15 days of requesting more information. Please add info requested so we can help move the issue forward. Note: The triage policy is to close stale issues that need more info and no response after 2 weeks.

github-actions[bot] avatar Apr 15 '22 02:04 github-actions[bot]

I tried the reproduction instructions (with https://fonts.googleapis.com/css?family=DM+Sans) and I see the same problem as reported above. I'm using [email protected], no Gutenberg plugin. The DM Sans font successfully loaded and applied in Desktop preview mode, but was missing in either of the two iframed previews.

@NenadObradovic there are other inconsistencies between the iframe preview modes and desktop preview, including this one I reported. Probably something the team will look at when building out the iframe editor more in the future.

ALJ avatar Apr 15 '22 03:04 ALJ

Hello @ALJ ,

I hope someone will check this issue :) In the meantime I fixed it with a not so good solution, but I can't wait for an answer :)

document.addEventListener(
	'DOMContentLoaded',
	function () {
		gutenbergResponsiveIframe.init();
	}
);

const gutenbergResponsiveIframe = {
	listenerTriggered: false,
	init: function () {
		const isEditorFrameLoaded = setInterval(
			() =>
			{
                                // Check is the current page Gutenberg editor or Full Site Editor
				const editorPage = document.querySelector( '.edit-post-visual-editor__content-area' ) || document.querySelector( '.edit-site-visual-editor' );

				if ( editorPage ) {
					clearInterval( isEditorFrameLoaded );

					gutenbergResponsiveIframe.listenerChanges( editorPage );
				}
			},
			500
		);
	},
	listenerChanges: function ( editorPage ) {

		const observer = new MutationObserver(
			() =>
			{

				if ( ! gutenbergResponsiveIframe.listenerTriggered ) {
					const editorFrame = editorPage.querySelector( 'iframe[name="editor-canvas"]' );

					if ( editorFrame ) {
						gutenbergResponsiveIframe.includeScripts( editorFrame.contentDocument );

						// Prevent function to include scripts only once for the full site editor
						if ( editorPage.classList.contains( 'edit-site-visual-editor' ) ) {
							gutenbergResponsiveIframe.listenerTriggered = true;
						}
					}
				}
			}
		);

		observer.observe(
			editorPage,
			{
				subtree: true,
				childList: true,
			},
		);
	},
	includeScripts: function ( $document ) {
		if ( $document ) {
			const $head  = $document.querySelector( 'head' );
			const styles = [];

			if ( typeof window.additionalIframeScripts === 'object' ) {
				for ( const [key, value] of Object.entries( window.additionalIframeScripts ) ) {
					styles.push( value );
				}
			}

			if ( styles.length > 0 ) {
				styles.forEach(
					styleURL =>
					{
						const link = $document.createElement( 'link' );

						link.setAttribute( 'href', styleURL );
						link.setAttribute( 'rel', 'stylesheet' );
						link.setAttribute( 'type', 'text/css' );

						$head.insertBefore( link, $head.firstChild );
					}
				);
			}
		}
	},
}

and inside functions.php I just localized the main block script for example

if ( is_admin() ) {
	wp_localize_script(
		'wp-block-editor',
		'additionalIframeScripts',
		array(
			'googleFonts' => esc_url_raw( 'https://fonts.googleapis.com/css?family=DM+Sans' ),
			'swiper'           => plugin_dir_url( __FILE__ ) ) . '/assets/plugins/swiper.min.css',
		)
	);
}

Best regards, Nenad Obradovic

NenadObradovic avatar Apr 15 '22 07:04 NenadObradovic

I've added class "wp-block" to my custom style, and now it's work. Thank you!

StasNemy avatar Jun 21 '22 23:06 StasNemy

I want to add that problem becomes more and more annoying because Wordpress has FSE priority in all updates. But still, we have no hooks, no functions to inject something inside FSE iframe.

For example, I also found that all hooks for Plugin for Sidebar is not working in FSE. And We also can't inject something in top toolbar of FSE, because it's placed inside iframe. Currently, I didn't find anything in documentation to extend FSE pages

wpsoul avatar Jul 14 '22 11:07 wpsoul

This issue is far more than just problem of assets. I found that all scripts which we add in editor (no matter how, with enqueue_block_editor_assets or with importing libraries in blocks) have no access to iframe because they are loaded outside iframe.

Scripts which will not work properly in Mobile preview and FSE:

  1. breakpoints for sliders, carousels - because scripts track general window and not iframe
  2. Custom drag and drop
  3. Any scroll tracking

We need a solution to load scripts in iframe. Currently, only styles are loaded there

wpsoul avatar Sep 13 '22 14:09 wpsoul

The ability to load custom scripts in the iframed editor should be resolved via #37466.

@wpsoul the Site Editor exports it's own PluginSidebar, PluginSidebarMoreMenuItem and PluginMoreMenuItem components.

import { PluginSidebar, PluginSidebarMoreMenuItem, PluginMoreMenuItem } from '@wordpress/edit-site';

There's also a dev note on how libraries used by blocks can adapt to iframed editors - https://make.wordpress.org/core/2021/06/29/blocks-in-an-iframed-template-editor/.

Mamaduka avatar Sep 13 '22 14:09 Mamaduka

@Mamaduka Plugin Sidebar was fixed already. It's just missing documentation information.

My message is about scripts in iframe.

https://make.wordpress.org/core/2021/06/29/blocks-in-an-iframed-template-editor/

This is not working. Problem is not in getting document, body, etc, I use Ref there. Problem is that many libraries require to load them in iframe to track iframe's data like breakpoints, scroll position, etc

https://github.com/WordPress/gutenberg/pull/37466 this is about styles, I can't see anything related to scripts. Styles already loaded in iframe so they have no problem

wpsoul avatar Sep 13 '22 14:09 wpsoul

Oustside of the work around shown by @NenadObradovic earlier, has anyone arrived at the "official" way to include external styles such as google fonts in the iframe preview?

It seems like there are two methods that are meant for getting styles into the editor. Using the add_editor_style function and enqueueing the style sheet in the enqueue_block_editor_assets hook.

As discussed here, enqueue_block_editor_assets won't work for something like google fonts because the style needs to have a wp-blocks selector to get added to the iframe preview.

#40469 indicates that add_editor_style should work, but it's super unclear from that function's documentation what it's intended to do. I thought that it was just for the old tiny mce editor, but apparently it's also used for the iframe preview? In any case when I've tried to use it to load google fonts it hasn't in the iframe preview.

@Mamaduka mentioned #37466 but it's still open. So I guess we can't use that method yet..

I might just be missing something obvious here but.. How am I suppose to get an external style sheet to load in the block editor iframe preview?

mark-c-woodard avatar Feb 03 '23 21:02 mark-c-woodard

Is there going to be a way that we can enqueue custom styles and scripts that will work in the preview iframe? It's especially annoying when patterns don't look like in the editor...

dingo-d avatar Mar 19 '23 17:03 dingo-d

I'm surprised that this wasn't thought of from the beginning. I am developing an FSE theme that uses the UIKit framework and ACF Blocks. This limitation has stopped me dead in my tracks. Essentially everything is broken without the ability to load external/3rd party JS libraries inside the editor iframe. I was not expecting that. I will have to revert to a classic theme. Disappointing.

GlentonCo avatar Apr 26 '23 19:04 GlentonCo

I want to add that problem becomes more and more annoying because Wordpress has FSE priority in all updates. But still, we have no hooks, no functions to inject something inside FSE iframe.

For example, I also found that all hooks for Plugin for Sidebar is not working in FSE. And We also can't inject something in top toolbar of FSE, because it's placed inside iframe. Currently, I didn't find anything in documentation to extend FSE pages

The lack of urgency around fixing this issue/limitation is infuriating. They want us to develop for FSE but how exactly are we supposed to do that? It's essentially unusable.

GlentonCo avatar Apr 28 '23 04:04 GlentonCo

Could someone clearly say if and how I can add CSS and JS files to the FSE iframe? Is that possible by now?

landwire avatar May 21 '23 07:05 landwire

@annezazu This issue is the one I meant in #35852

dingo-d avatar May 21 '23 08:05 dingo-d

Just a quick note saying that I've added the blocks adoption label here to better track the impact of this problem!

annezazu avatar May 22 '23 19:05 annezazu

This affects also the plugin JVM Gutenberg Rich Text Icons — Block Editor shows whitespace instead of inline icon due to CSS not being loaded properly within the Editor environment:

WordPress JVM Gutenberg Rich Text Icons - Block Editor shows whitespace instead of inline icon

porg avatar Jul 03 '23 12:07 porg

Could someone clearly say if and how I can add CSS and JS files to the FSE iframe? Is that possible by now?

That is all I'm looking for. Can we load JavaScript in the FSE iframe? A simple yes or no would be great.

It's been a year and six months. SMH.

GlentonCo avatar Jul 05 '23 13:07 GlentonCo

That is all I'm looking for. Can we load JavaScript in the FSE iframe?

You can't load currently. I believe that next WP update will introduce new action which can be used if you want to load something in iframe

wpsoul avatar Jul 05 '23 18:07 wpsoul

@sitestudioapp Only blocks could previously add script handles to load into the iframe. From WP 6.3, you can use the enqueue_block_assets action to load any asset into the iframe that is also loaded on the front-end. See #49655.

ellatrix avatar Jul 06 '23 07:07 ellatrix