Use JavaScript in a file included in the HTML with <script>
Generally, you should do DOM manipulations from within JavaScript loaded with a <script>
tag within your popup.html, just like you would for a browser action popup or options page. For example from JavaScript in a popup.js file and included in popup.html like:
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<input type="text" id="txtField" />
</body>
</html>
Actually manipulating the DOM of the new window from the opener
If you are wanting to access the Window of a popup, you will need to get a view for it using chrome.extension.getViews()
. This is complicated by the fact that the window does not actually exist yet when the callback from chrome.windows.create()
is executed, or when a chrome.windows.onCreated
listener (or windows.onFocusChanged
) is called (both fire before the chrome.windows.create()
callback is executed). There does not appear to be an event which will notify you when the new popup window actually exists, or when you can get a view for it.
Thus, you are much better off using code in a JavaScript file which is included in the HTML using a <script>
tag.
If you still desire to manipulate the DOM of the opened window, you are going to have to poll until you find a view for it. The following will do what you want:
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({"url": "popup.html", "type": "popup"}, function(wd){
waitForWindowId(winObject.id,50,20,function(view){
console.log(view);
view.document.getElementById("txtField").value = "asd";
});
})
});
function waitForWindowId(id,delay,maxTries,callback) {
let where = 'watchForWindow';
if(maxTries--<=0){
//Fail softly. You may want to do something else on failure to find the new window.
return;
}
//This type of window is a type:'tab', not type:'popup'.
if(!chrome.extension.getViews({windowId:id}).some(view=>{
if(typeof callback === 'function'){
callback(view);
}
return true;
})){
//Did not find the view for window ID. Keep trying
setTimeout(waitForWindowId,delay,id,delay,maxTries,callback);
}
}