从script.js更改popup.html的内容?

时间:2018-03-24 18:37:38

标签: javascript html google-chrome-extension

我正在制作Chrome扩展程序,我正在向某个URL发送一个ajax请求,该URL返回JSON数据并且工作正常,但我想在扩展程序上显示该数据。

的script.js

var link = location.href;

$(document).ready(function() {
   url(link);
})

function url(link) {
 // use "link" variable to get the link here

var data = {js_link: link}
$.ajax({
   console.log("2"); // THIS IS PRINTING ON THE CONSOLE
   url: 'some url',
   data: JSON.stringify(data),
   type: 'POST',
   success: function (response) {
     console.log(response.score); //This works
     document.getElementById('score').innerHTML=response.score;
   },
   error: function (error) {
       console.log("ERROR");
       console.log(error);
   },
   dataType: "json",
   contentType: 'application/json;charset=UTF-8',
});

}
console.log("1");

popup.html

<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</head>
<body style="width:450px; height:420px;margin-top:10px;">
  <div class="container">
    <div class="row">
      <div class="col-10 col-offset-2">
        <h3>Moderator</h3>
      </div>
    </div><hr/>
    <div class="row">
      <div class="col-10 col-offset-2">
        <h6>Polarising index is <div id="score">8</div></h6>
      </div>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>

 </body>
 </html>

的manifest.json

{
"name": "Hello Extensions",
"description" : "Base Level Extension",
"version": "1.0",
"manifest_version": 2,
"browser_action": {
  "default_popup": "popup.html",
  "default_icon": "icon.png"
},
"content_scripts": [{
  "matches": ["https://*/*","http://*/*"],
  "js": [ "jquery.js","script.js"]
  }
],
"permissions": [
  "tabs","http://*/*"
],
"background": {
  "scripts": ["background.js"]
  },
"commands": {
  "_execute_browser_action": {
    "suggested_key": {
      "default": "Ctrl+Shift+F",
      "mac": "MacCtrl+Shift+F"
    },
    "description": "Opens hello.html"
  }
}
}

此外,在刷新页面后,console.log(response.score)会出现稍晚。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

HTML

<html>
  <head>
    <title>Hello Extensions</title>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="script.js"></script>
  </head>
  <body style="width:450px; height:420px;margin-top:10px;">
  <div class="container">
    <div class="row">
      <div class="col-10 col-offset-2">
        <h3>Moderator</h3>
      </div>
    </div><hr/>
    <div class="row">
      <div class="col-10 col-offset-2">
        <h6>Polarising index is <div id="score">8</div></h6>
      </div>
    </div>
  </div>

</html>

的script.js

document.addEventListener('DOMContentLoaded', function() {
    console.log("DOMContentLoaded");
    Load();
}, false);

var link = location.href;

function Load() {
    url(link);
}

function url(link) {
    console.log("AJAX Start");
    var data = {js_link: link}
    $.ajax({
        url: 'some url',
        data: JSON.stringify(data),
        type: 'POST',
        success: function (response) {
            console.log("AJAX Success. SCORE =>");
            console.log(response.score); //This works
            document.getElementById('score').innerHTML=response.score;
        },
        error: function (error) {
            console.log("AJAX Error. Error =>");
            console.log(error);
        },
        dataType: "json",
        contentType: 'application/json;charset=UTF-8',
    });

}

答案 1 :(得分:0)

在您的脚本中尝试此操作

var link = location.href;

$(document).ready(function() {
  url(link);
});

function url(link) {
    var data = {js_link: link}
    $.ajax({
        url: 'some url',
        data: JSON.stringify(data),
        type: 'POST',
        success: function (response) {
            console.log(response.score); //This works
            document.getElementById('score').innerHTML=response.score;
        },
        error: function (error) {
            console.log("ERROR");
            console.log(error);
        },
        dataType: "json",
        contentType: 'application/json;charset=UTF-8',
    });

}

答案 2 :(得分:0)

看起来您可能误解了浏览器扩展的结构。您在清单中将script.js声明为内容脚本。这意味着它将被注入到用户所访问的每个页面中 - 可能不是您想要的。 (您可能希望获得某些内容以获取任何给定页面的URL,但请参阅最后一段。您可能希望每次用户访问任何页面时都触发Web请求,这是你目前的设置。)

此外,正如其他人所指出的那样,script.js console.log("2")处的语法错误。请使用您遇到问题的真实代码更新您的问题,因为您目前的代码甚至无法运行。

此外,由于extension content security policies,您将无法在弹出窗口中从外部URL加载JQuery或popper.js。如果您想使用它们,最简单的方法是将本地副本下载到与项目相同的文件夹中,并从popup.html引用它们(看起来您已经在本地拥有jquery.js的副本,因为你在清单中引用了它。

最后,您在这里寻找的功能是什么?如果您想根据当前标签页面在弹出窗口中显示某些内容,那么您不需要内容脚本来获取location.href。当您的弹出窗口被打开时,您可以将其send a message添加到您的后台页面,该页面可以使用Chrome的tab API获取当前标签的网址并将其返回到弹出窗口。