How To Get Elements From A Webpage DOM Into My Background.js?
I`m trying to make an extension for Chrome that automatically logs in to this web page. It does this by detecting when I enter the page, then it redirects the browser to the login
Solution 1:
Background scripts can't interact directly with the DOM of regular pages. When you use document
in a background script, you are referring to the DOM of the background page that Google Chrome creates for your extension.
To access the DOM of web pages you need a content script. You can specify it in the manifest or inject it programmatically using chrome.tabs.executeScript
. As in your case you want to always run it in a specific URL the easiest way is via the manifest:
"content_scripts": [
{
"matches": ["https://vaf.itslearning.com/elogin/"],
"js": ["content.js"]
}
],
And in your content.js you can put:
var username = document.getElementById("ctl00_Username");
var password = document.getElementById("ctl00_Password");
var button = document.getElementById("ctl00_ButtonLogin");
if (username && password && button) {
username.value = "####";
password.value = "######";
button.click();
}
So in your background.js you only need to leave the redirect code:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (tab.url == "https://www.itslearning.com/Index.aspx?customerid=&username=&redirectlogin=itslearning.com&MustUseSsl=true&")
chrome.tabs.update(tabId, {"url": "https://vaf.itslearning.com/elogin/"});
}
(BTW, there are more efficient ways to cause a redirect using chrome.webRequest
)
Post a Comment for "How To Get Elements From A Webpage DOM Into My Background.js?"