16
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Chrome Extentionでinlineのjavasciptが書けない

Posted at

#ChromeExtentionでscriptタグを用いてinlineでjavascriptが書けない
表題の件でハマった。
実際、ChromeExtentionのドキュメントには書いてあるのだが、メモしておきます。
以下のようなhtmlは、エラーで動きませんでした。

popup.html
<!DOCTYPE html>
<html lang="jp">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>PopupSample</title>
    <link rel="stylesheet" href="css/popup.css" type="text/css">
</head>

<body>
        <script>
        	function log(){
        		console.log("click");
        	}
        </script>
        <button type="button" onclick="log();">クリック</button>
</body>

</html>
manifest.json
{
    "name": "Sample",
    "version": "1.0",
    "manifest_version": 2,
    "description": "sample",
    "content_security_policy": "script-src 'self'; object-src 'self'",
    "browser_action": {
        "default_popup": "popup.html",
        "default_icon": "images/sample_16.png"
    },
    "permissions": [
        "tabs"
    ],
    "icons": {
        "16": "images/sample_16.png",
        "48": "images/sample_48.png",
        "128": "images/sample_128.png"
    }
}

###ボタンを押した際に出力されたエラー

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

##解決策
外にjsを切り出してHandlerを定義するとjavascriptを動かすことができます。

popup.html
<!DOCTYPE html>
<html lang="jp">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>PopupSample</title>
    <link rel="stylesheet" href="css/popup.css" type="text/css">
    <script src="popup.js"></script>
</head>

<body>
    <button type="button" class="btn">クリック</button>
</body>

</html>
popup.js
function clickHandler(e) {
    console.log("click");
}

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('.btn').addEventListener('click', clickHandler);
});
16
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?