简体   繁体   中英

Change content of popup.html from script.js?

I am making a chrome extension, I am sending an ajax request to some URL which returns JSON data and it works perfectly, but I want to display that data on the extension.

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"
  }
}
}

Also, console.log(response.score) appears a little late after the page is refreshed. Any help is appreciated.

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',
    });

}

Try this in your script

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',
    });

}

It looks like you may have misunderstood the structure of a browser extension. You're declaring script.js in your manifest as a content script . This means that it's going to be injected into every single page the user goes to - probably not what you want. (You might want to have something to get the URL of any given page, but see the last paragraph for that. You probably don't want to be triggering a web request every time the user visits any page, which is what your current setup does.)

Also, as others have pointed out, you have a syntax error in your script.js at console.log("2") . Please update your question with the real code you're having trouble with, as the code you have currently wouldn't even run.

Also, you won't be able to load JQuery or popper.js from an external URL in your popup, because of extension content security policies . If you want to use them, the easiest way is to just download local copies to the same folder as your project and reference them from your popup.html (it looks like you already have a copy of jquery.js locally, since you're referencing that in your manifest).

Finally, what is the functionality you're looking for here? If you want to show something in the popup based on the current tab url, then you don't need a content script just to get a location.href . When your popup gets opened, you can have it send a message to your background page, which can use Chrome's tab API to get the URL of the current tab and return it to the popup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM