I have a .js file that largely works. Except that a line with a selector and its subsequent console log returns nothing. I tried the code in the console and it works: console log returns what I was expecting. Then the question is, why doesn't it work in the script file? To zone in on the issue, I've commented out every other line in the script. It still doesn't work. What could be wrong in these mere 4 lines? -- they are now all there is in the script file.
$( document ).ready(function() {
alert("alert");
var fullname2 = $('#topcard').find('.profile-info').find('h1').text().replace(/ /g, '_');
console.log(fullname2);
});
The alert fires, both if I run the code in console, or if I run the .js script.
The above is code in the content.js that is part of a Chrome extension. So I confirmed that the bug is something related to running the .js file before the document is ready, by the following: if I use setTimeout, the bug seems to disappear from running the js. script:
setTimeout(function(){
console.log("hello");
$(document).ready(function() {
var fullname2 = $('#topcard').find('.profile-info').find('h1').text();
console.log(fullname2);
});
}, 2000);
By running the script, console logs the fullname correctly.
I found out that setting "run_at" in the manifest.json may make a difference. But I so far haven't made it work. Since the default was "document_idle" and it didn't work when I didn't specify run_at, now I set it as "run_at": "document_end". But it still doesn't work without the setTimeout.