I am trying to get some data from a webpage and pass it to new window and print it from there. Here is my code:
var print_btn;
let win;
document.getElementsByTagName('html')[0].innerHTML = document.getElementsByTagName('html')[0].innerHTML +"<button class=\"printbuton\">Print Button</button>";
print_btn = document.getElementsByClassName('printbuton')[0];
print_btn.onclick = function() {
console.log("check 1");
var WinPrint = window.open('', '', 'left=0,top=0,width=384,height=900,toolbar=0,scrollbars=0,status=0');
console.log("check 2");
WinPrint.document.write('Print this');
console.log("check 3");
WinPrint.document.write('Print that');
WinPrint.document.write('and this');
console.log("button pushed");
}
When I try this it opens the new window, but it stays empty and in console it logs only "check 1" and "check 2".
I tested that if i console.log(WinPrint) it shows in console, but if I do console.log(WinPrint.document) it doesn't show anything and the script stops there.
Your code will not work due to a (XSS [Cross Site Scripting]) Error. Firefox is preventing you from altering the content of a different domain.
Since you're opening a new window, you now have a different domain name (about:blank) than the one you started on.
There's a few ways to go about this, what comes quickly to mind would be to use the window.create API and use query params to pass the data to the new window:
function onCreated(windowInfo) {
console.log('SUCCESS');
}
function onError(error) {
console.log(`Error: ${error}`);
}
print_btn.addEventListener('click', event => {
var popupURL = browser.extension.getURL("popup/popup.html?line=blahblah&line2=loremipsum");
var creating = browser.windows.create({
url: popupURL,
type: "popup",
height: 200,
width: 200
});
creating.then(onCreated, onError);
});
Or you could do something more elaborate by opening using windows.create, then using runtime.sendmessage to pass messages back to the background script and then to the new window.
OR you could probably inject a popup into the page itself and do something similiar.
Related
I'm working with a Google-Extention which allows me to open a new tab containing a form. After the form gets filled out and saved, every time I open this tab again the form should be prefilled with the data saved earlier.
Here is how the data gets saved: WORKS!
function saveCheckoutData() {
var vName = document.getElementById('txbx_name').value;
chrome.storage.sync.set({'name': vName}, function() {
console.log(vName);
})
}
Here is how i get the data: WORKS!
function getdata() {
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
The code above gets called on button click and works perfectly!
But as soon I try to do this when the tab gets opened it doesn't work (the tab gets opened but there is nothing in the textbox): DOESN'T WORK!
function configAutofill(){
var newURL = "autofill_data.html";
chrome.tabs.create({ url: newURL });
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
Does some one have an Idea why these lines do not work when creating a new tab?
Many thanks in advance.
Here's a question for you.
After creating a new tab, you access document.getElementById. Yes, but which document?
In your case, it would be the page calling create - which is not the created page.
In your case, it seems like you're opening a page that's part of the extension. Then you should just include code in it that will run on load.
You may want to check document.readyState:
if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', getdata);
} else {
getdata();
}
If you're trying to do this with a webpage, you'll need a content script. Again, those normally execute after DOM is parsed - so just call getdata() at top level.
Below is the piece of code I am using to open a link in a new window say "abc".
If the user again clicks on the same link, it should close and reopen the link in the same window "abc".
window.openOrFocus = function(url, "abc") {
if (!window.popups) {
window.popups = {};}
if (window.popups["abc"]){
var v=window.open("", "abc");
v.close();}
window.popups["abc"] = window.open(url, "abc");
}
But Now, say I click on the link, it opens the URL in a new window named "abc".
Now I go and close the window "abc". and go back and again click on the link.
That time it shows up the pop up blocker.
I am confused as to why this pop up blocker is coming when the I go and manually close the window and try to reopen by clicking on the link.
Happens both in IE as well as Chrome
Probably because you're calling window.open with a blank URL or repeatedly in that case.
You don't need your window.open("", "abc") call; instead, just use the window reference you already have:
window.openOrFocus = function(url, windowName) {
if (!window.popups) {
window.popups = {};
}
if (window.popups[windowName]){
window.popups[windowName].close();
}
window.popups[windowName] = window.open(url, windowName);
};
I would also listen for the unload event so you can remove your reference:
window.openOrFocus = function(url, windowName) {
if (!window.popups) {
window.popups = {};
}
if (window.popups[windowName]){
window.popups[windowName].close();
}
window.popups[windowName] = window.open(url, windowName);
window.popups[windowName].onunload = function() {
delete window.popups[windowName];
};
};
Side note: This is a syntax error:
window.openOrFocus = function(url, "abc") {
// --------------------------------^
I've replaced it with windowName in the code above.
I am new to pdf.js and google chrome extensions. I am using pdf.js to view PDF files in Chrome (https://github.com/mozilla/pdf.js/tree/master/extensions/chromium).
WHAT I WANT TO IMPLEMENT: Once my PDF is loaded and processed by PDF viewer (pdf.js), I want to check if a user is logged into my website via XmlHttpRequest. Then I want to create a popup window showing the user's name or ask him/her to login.
I've added checkLogin(); function to the following script (https://github.com/Rob--W/chrome-api/tree/master/chrome.tabs.executeScriptInFrame).
checkLogin(); opens a new popup window (dialog.html)
chrome.tabs.executeScriptInFrame.js :
function checkLogin() {
chrome.tabs.create({
url: chrome.extension.getURL('dialog.html'),
active: false
}, function(tab) {
// After the tab has been created, open a window to inject the tab
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true,
height: 200, width:500
});
});
}
dialog.html displays the message returned from dialog.js (containing username or asking user to login)
dialog.html :
<html>
<head><title>Dialog test</title></head>
<body>
<div id="output"></div>
<script src="dialog.js"></script>
</body>
</html>
dialog.js :
connect();
function connect() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "sendingcookies.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status ==200 ) {
var response = xhr.responseText;
document.getElementById('output').innerHTML = response;
}
}
xhr.send(null);
}
THE PROBLEM: If I insert checkLogin(); function in background.js, the script runs when the extension is loaded. However, I want to run this function each time a PDF is loaded and processed by pdf.js. I am not sure how to proceed as I'm still familiarizing with pdf.js code.
Any tips on how to implement this correctly will be awesome. Thanks in advance for your help!
So I figured out how to implement this. I'm posting this answer for those that may be interested.
As suggested by user #Luc on the thread How to know if PDF.JS has finished rendering? , I added my checkLogin(); function to this existing function in viewer.js.
document.addEventListener('textlayerrendered', function (e) {
var pageIndex = e.detail.pageNumber - 1;
var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
//Added this code - creates popup window once PDF has finished rendering
if (event.detail.pageNumber === PDFViewerApplication.page) {
checkLogin();
function checkLogin() {
chrome.tabs.create({
url: chrome.extension.getURL('dialog.html'),
active: false
}, function(tab) {
// After the tab has been created, open a window to inject the tab
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true,
// incognito, top, left, ...
height: 300, width:500
});
});
}
}
}, true);
As a result, my popup window loads while/once the PDF has finished rendering. It's pretty neat!
I am opening a new window when a button is clicked and then appending the content from this window to the window that has been opened, the jQuery code that I'm using is:
$(".printBtn").on("click", function () {
var w = window.open("", "Purchase Report", "width=800, height=1100");
var wi = $(window);
$(w.document.body).append(wi.find("#datatable_example"));
return false;
});
The problem is, a new window does open but the content from the parent window is not being appended to the newly opened window. I then tried to append wi.find("#datatable_example").html() but that didn't work either.
Can any one please have a look and tell me what I am doing wrong here?
UPDATE
Tried the following from the "duplicate question", but didn't work:
$(".printBtn").on("click", function () {
var w = window.open("", "Purchase Report", "width=800, height=1100");
$(w.document).ready(function () {
$(w.document.body).contents().append($(window).find("#datatable_example"));
});
return false;
});
The problem was, I was using var wi = $(window) instead of var wi = $(window.document). Here is the working code:
$(".printBtn").on("click", function () {
var w = window.open("", "Purchase Report", "width=800, height=1100");
var wi = $(window.document);
$(w.document.body).append(wi.find("#datatable_example"));
return false;
});
The root of your problem is same origin policy that won't let you observe load events for external domains. If you try this in developer console while browsing SO, everything's fine:
var child = window.open( 'http://stackoverflow.com' );
child.onload = function() {
alert( 'Popup loaded!' ); // Fired!
};
However if you try to open a page from other domain, it fails:
var child = window.open( 'http://stackexchange.com' );
child.onload = function() {
// It's not gonna be fired unless you run it from stackexchange.com.
alert( 'Popup loaded!' );
};
The same thing happens when you call window.open() or window.open( '' ) as it tries to load about:blank page which is out of your domain's scope and that's why your browser won't fire attached events (same for child.addEventListener( 'load' )). Also note that the protocol must match as well.
The workaround introduces setTimeout to run the callback in a separate JS thread, hopefully late enough to have DOM ready at that time:
var child = window.open();
setTimeout( function() {
var doc = child.document,
p = doc.createElement( 'p' );
p.innerHTML = 'Hello world!';
doc.body.appendChild( p );
} );
It works for me in latest Chrome, however different browsers sometimes do strange thing in such edge cases so you may need to tune this code with greater delay, sequential check or something else if it fails in your case.
So go ahead and tell us if it worked for you as I'm curious whether such workaround is fine for production code ;)
I am developing a small extension( https://docs.google.com/leaf?id=0B5ZSnXcRXnSpMmM0NTFiNGEtMzEzZS00M2YzLWI4MzItMmVmNmM3OGE1MDRh&hl=en&authkey=CLzGpOMN ) that saves all tabs in a particular window, while closing that session.
In this, when I am trying to restore the session, I am not getting callback function getting called, though the new window is successfully opened.
The funny thing is, when in developer mode, using developer tools, the callback function gets called and restored all tabs.
Please help me.
Here is the code:
function restoreTabs( saveTabName )
{
var tabVals = window.localStorage.getItem(saveTabName);
if (tabVals == null)
return;
var callbackFunc = function (window, tabValList) {
//alert('created window');
for (var i = 0; i < tabValList.length; i++) {
var tab = eval('(' + tabValList[i] + ')');
var newTabObj = {
windowId: window.id,
index: tab.index,
url: tab.url,
selected: tab.selected,
pinned: tab.pinned
};
chrome.tabs.create(newTabObj);
}
};
var tabValList = tabVals.split('|');
chrome.windows.create(null, function (win) { callbackFunc(win, tabValList); });
}
Interesting problem. Popup is getting automatically closed when you create a new window (and as a result popup code execution is terminated), that's why it works in developer mode only because it forces the popup to stay open. You need to move restoreTabs() function to a background page, you can still easily call it from your popup:
linka.onclick = function () {
chrome.extension.getBackgroundPage().restoreTabs('saveTabs'+savetabName);
};