I am making a chrome extension that will take come content from the current selected tab. I am injecting a script file into the current page and that script communicates with the script from the extension. With the javascript injected in the page I am trying to load jQuery so it is easier to find the content I want.
(function() {
var script = document.createElement('script');
script.setAttribute("src", "http://code.jquery.com/jquery-latest.min.js")
script.setAttribute("type","text/javascript")
script.onload = script.onreadystatechange = function(){
var port = chrome.runtime.connect({name: "ext"});
port.postMessage({ images: getImages(document)});
port.onMessage.addListener(function(msg) {
if (msg.request == "message")
port.postMessage({ message: getText(document)});
});
};
document.body.appendChild( script );
function getText(doc) {
var textString = $("div[id*='message'],div[class*='message']").filter(function() {
return /[0-9]/.test( $(this).text() );
}).html();
var text = textString.match(/\d+/);
return text;
}
function getImages(doc){
var result = "";
var images = document.getElementsByTagName("IMG");
for(var i = 0; i < images.length; i++){
if(images[i].height > 200 && images[i].width > 200){
result = result + images[i].src + ",";
}
}
return result;
}
})();
The jQuery library gets loaded (I checked the 'Network' tab in the Developer tools) and the code gets into the getText() function, but '$' is undefined.
EDIT:
script.onload = script.onreadystatechange = ...
is the code that is waiting for the jQuery to be loaded. And it is getting in there. But when it gets to
var textString = $("div[id*='message'],div[class*='message']")
'$' is undefined