こんにちは、CX事業本部 Delivery部の若槻です。
DevelopersIO は CMS として WordPress が使われており(詳細はこちら)、権限があるユーザーは記事ごとの編集ページで記事の作成や編集を行います。
今回は、DevelopersIO の記事ページに「編集」ボタンを表示し、クリックしたら WordPress の編集ページに遷移できる Chrome 拡張を作ってみたので紹介します。
これにより、記事に typo などを見つけた際に、即座に編集ページに遷移して記事の修正を行うことが出来るようになります。なお、作成した Chrome 拡張のストア公開は現時点ではしていません。(そのうちやるかも知れません)
作ったもの
次の4ファイルから成る Chrome 拡張を作りました。
- content.js
- styles.css
- background.js
- manifest.json
それぞれ解説していきます。
content.js
content.js
では、ページの表示時にボタン要素を配置しています。ボタンをクリックするとその記事の編集ページが開く処理が実行されます。
content.js
// ページの表示時にヘッダー右側にボタンを配置する
window.onload = () => {
const header = document.querySelector('#__layout > div > div > header');
const spacer = header.querySelector('.spacer');
const link = document.createElement('a');
link.textContent = '編集';
link.className = 'editor-link';
link.addEventListener('click', openEditor);
spacer.parentNode.insertBefore(link, spacer);
};
// ボタンクリック時に編集ページを開く
const openEditor = () => {
// ページの DOM 要素から記事 ID を取得する
const scriptContent = document.querySelector(
'body > script:nth-child(3)'
).textContent;
const postIdMatch = scriptContent.match(/id:(\d+),/);
if (postIdMatch) {
const postId = postIdMatch[1];
window.open(
`https://dev.classmethod.jp/wp-admin/post.php?post=${postId}&action=edit`,
'_blank'
);
}
};
ボタンクリック時に記事ページの DOM 要素から記事 ID をパースし、その ID を使って編集ページの URL 組み立てて開いています。
styles.css
Chrome 拡張では CSS ファイルを使用できます。styles.css
でボタンのスタイルを定義しています。
styles.css
.editor-link {
float: right;
margin-top: 10px;
margin-right: 10px;
padding: 5px;
background-color: #007ACC;
color: white;
text-decoration: none;
border-radius: 5px;
height: 40px;
cursor: pointer;
}
実際に配置されたボタンのデザインはこのようになります。(デザインセンスをもっと磨きたい)
background.js
Service Worker として動作する background.js
です。今回の拡張機能では実際の処理は content.js
で行うようにしているため Service Worker 自体の処理はシンプルにしてあります。
background.js
console.log('Background service worker running');
Chrome 拡張機能のコンテキストでは、Service Worker は、ブラウザや拡張機能のイベントをリッスンしたり、特定のタスクをバックグラウンドで実行したりするイベントハンドラとして使用されます。
manifest.json
Chrome 拡張のマニフェストファイルです。現在推奨されているマニフェストバージョンは 3 のため、本マニフェストでも使用しています。(2 を指定するとワーニングが発生します)
manifest.json
{
"manifest_version": 3,
"name": "Open Editor on developersIO",
"version": "1.0",
"description": "Add an 'Edit' link to developersIO article pages to open the editor",
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://dev.classmethod.jp/articles/*"],
"js": ["content.js"],
"css": ["styles.css"]
}
]
}
※追記:"permissions": ["activeTab"]
が不要なことが分かったので記述削除。
動作確認
Chrome 拡張のインストール
Load unpacked から Chrome 拡張をローカルフォルダよりインストールします。(この時 Developer mode が有効化されている必要があります)
使ってみる
記事ページを開くと、ヘッダー右側に「編集」ボタンが表示されています。
ボタンをクリックすると、記事の編集ページに遷移しました!
おわりに
DevelopersIO の記事ページに「編集」ボタンを表示し、クリックしたら WordPress の編集ページに遷移できる Chrome 拡張を作ってみたので紹介しました。
WordPress の記事一覧から修正したい記事を検索して探すのは手間だったので、これでその手間を省くことができました。
以上