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

Categories

I've looked at the other answers but still don't understand.

For some reason this line of code always returns null.

var els = document.querySelector("[id='MTG_INSTR$2']");

I checked the value of document in the console so I'm pretty sure that's correct.

The id is buried deep inside a table though, could that be an issue?

EDIT 2: If it helps, here's the full code.

content.js

chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if( request.message === "start" ) {
         start();
             }
      }
    );

    function start(){
        var els = document.querySelector("[id='MTG_INSTR$2']");
        console.log(els);
        alert("started");
    }

popup.html

<!DOCTYPE html>
<html>
<head></head>
<script src="popup.js"></script>
<body>
<input id="button1" type=button value=clickme>
</body></html>

popup.js

 function popup() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
   });
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("button1").addEventListener("click", popup);
});

manifest.json

{
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "manifest_version": 2,
  "name": "extensiontest",
  "version": "0.2",
  "content_scripts": [
  {
    "matches": [
      "<all_urls>"
    ],
    "js": ["content.js"]
  }
],
"browser_action": {
  "default_icon": "icon.png",
    "default_popup":"popup.html"
},
//"background": {
// "scripts": ["background.js"]
//},
"permissions": [
    "tabs"
  ]
}

EDIT: I've included a screen shot of what the document structure looks like.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

I doubt your JS gets loaded before the markup and css. In that case, you could try using <script src="" defer></script>

The contents are loaded first and your java script should work fine after that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...