Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

jquery - Chrome showing error as: Refused to execute inline script because of Content-Security-Policy

I am working on creating a Chrome Extension of an Image Cropping Widget. The code of my popup.html is as follows:

<body>
    <textarea id="widget_script" style="border:1px solid #ccc;padding:5px;width:600px" rows="5" readonly></textarea>
    <script type="text/javascript">
        var protocol=window.location.protocol;
        var host= window.location.host;
        var head=('<div id="wd_id" style="margin-bottom: 20px;"></div>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="'+protocol+'//'+host+'Image_crop/cropimages/img_crop_widget.js'+'"></script>
    <script type="text/javascript">init_widget()</script>');
        document.getElementById("widget_script").innerHTML=head;
    </script>
</body>

The variables protocol and host take protocol and host from URL in the browser. When I tried to integrate this as a Chrome extension, it is not working. When it works perfectly, it displays following code in the textarea:

<div id="wd_id" style="margin-bottom: 20px;"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://localhost/cropimages/img_crop_widget.js"></script>
<script type="text/javascript">init_widget()</script>

I have things few things like, placing the JS code in external JS file and and also calling the file in manifest.json calling it in my popup.html, but none worked.

Can anyone tell me what I am doing wrong, or what else should I try to make it work?

Thanks in advance...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the Chrome extension CSP docs:

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

You cannot have inline scripts in your extension HTML like:

<script>alert("I'm an inline script!");</script>

<button onclick="alert('I am an inline script, too!')">

Rather, you must place your script into a separate file:

<script src="somescript.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...