メインコンテンツへスキップ

JavaScript API

WordPress Playground には、WordPress を完全に制御できる JavaScript API クライアントが付属しています。

ここでの API は「REST API」を意味するものではありません

WordPress Playground はブラウザベースのアプリケーションです。 ここでの API とは、JavaScript 内で呼び出せる関数のセットを指します。 これはネットワークベースの REST API ではありません。

クイックスタート

JavaScript API を使用するには、次のものが必要です。

  • <iframe> 要素
  • @wp-playground/client パッケージ(npm または CDN から)

HTML ページで JavaScript API を使用する最も短い例を次に示します。

<iframe
id="wp"
style="width: 100%; height: 300px; border: 1px solid #000;"
></iframe>
<script type="module">
// Use unpkg for convenience
import { startPlaygroundWeb } from 'https://playground.wordpress.net/client/index.js';

const client = await startPlaygroundWeb({
iframe: document.getElementById('wp'),
remoteUrl: `https://playground.wordpress.net/remote.html`,
});
// Let's wait until Playground is fully loaded
await client.isReady();
</script>
/remote.html は特別な URL です

/remote.html は、ブラウザ UI を備えたデモアプリではなく、Playground API エンドポイントを読み込む特別な URL です。//remote.html の違いについては、このページ をご覧ください。

ウェブサイトの制御

client オブジェクトが作成されたので、これを使って iframe 内のウェブサイトを制御できます。制御方法は 3 つあります。

デバッグとテスト

迅速なテストとデバッグのために、JavaScript API クライアントは index.htmlremote.html の両方で window.playground として公開されます。

> await playground.listFiles("/")
(6) ['tmp', 'home', 'dev', 'proc', 'internal', 'wordpress']

index.html では、playground は Proxy オブジェクトなので、ブラウザによる自動補完は利用できません。ただし、remote.html では、playground はクラスインスタンスなので、ブラウザの自動補完を利用できます。