To run JavaScript for Chrome extensions,
JavaScript runs faster in the site
Is there a way to describe it first?
For example, on a site like this,
<body>
<divid="t">test</div>
<script>
start = document.getElementById('t');
vars = t.innerHTML;
t. innerHTML = s.replace('test', 'sample');
</script>
</body>
InnerHTML in id="t" in this way
Even if you try to display it in console.log,
What actually appears is
replace replaced.
You will end up with the string sample
chrome.tabs.onUpdated.addListener(function(){
chrome.tabs.executeScript(null,{
'code': 'console.log( document.getElementById("t").innerHTML)'
});
});
To display the test string before replacement
What should I do?
You can add Content script to the extension so that it runs ("run_at":"document_start"
) when the page starts loading.
manifest.json
{
"manifest_version"—2,
"name": "My extension",
"version": "1.0.0",
"content_scripts":[
{
"matches": ["http://*/*", "https://*/*", "file://*",
"run_at": "document_start",
"js": ["script.js" ]
}
]
}
You can then monitor the DOM changes in script.js in MutationObserver to obtain the values before the script runs in the page.
script.js
(function(){
varMutationObserver=window.MutationObserver||window.WebKitMutationObserver;
varobserver = new MutationObserver(function(mutations){
Array.prototype.forEach.call(mutations, function(mutation){
if(mutation.type==='childList'){
Array.prototype.forEach.call(mutation.addedNodes, function(node){
if(node.id==='t'){
console.log(t.innerHTML);
}
});
}
});
});
observer.observe( document, {
attributes:true,
childList:true,
characterData: true,
subtree —true
});
})();
After loading the HTML page for the example question, the console will print the test
properly.
© 2024 OneMinuteCode. All rights reserved.