0

I want to create a chrome extension, to run HTML validator on a webpage.

chrome.browserAction.onClicked.addListener(function(tab){
   chrome.tabs.executeScript(tab.id, {file: "inject.js"}, function(){
    alert(results);
});});

Below id the code in inject.js

var js = document.createElement("script");

js.type = "text/javascript";
js.src = "https://cdnjs.cloudflare.com/ajax/libs/html-inspector/0.8.1/html-inspector.js";

document.body.appendChild(js);

HTMLInspector.inspect();

On the DOM, I see that the script tag is added above the body tag. But the line HTMLInspector.inspect(); throws the error. What can I do to fix this?

Hozefa
  • 1,676
  • 6
  • 22
  • 34
  • It throws an error, because the script is loaded asynchronously, but you are trying to use the object immediately without waiting for the script to be done loading. // There are a lot of solutions already out there to dynamically load scripts; go take a look at a few of them, how they implement a `load` event/callback that fires when the script is done loading. – CBroe Jan 24 '15 at 05:28
  • @Felix: This is a Chrome extension-specific error and has nothing to do with the linked duplicate. Please use dupehammer responsibly. P.S.: Nevermind, saw the edit history, relevant information was added only now. Still a bad dupe though. – Xan Jan 26 '15 at 10:37

1 Answers1

0

try like this if you are using jquery: add it to head.

<script>
 var js = document.createElement("script");
 js.type = "text/javascript";
 js.src = "https://cdnjs.cloudflare.com/ajax/libs/html-inspector/0.8.1/html-inspector.js";
 $("head").append(js)
 window.onload = function() {
 HTMLInspector.inspect();
 }
</script>
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44