How to access data of the opened tab using javascript - javascript

I have mentioned the code below which I have been trying. I am successfully able to open a url in a new tab but unable to access the content using DOM. so someone please suggest me any ideas how to access the data...
Thank you in advance.
<html>
<head>
<script>
var url = "www.website.com";
var Tab = window.open(url);
var Name = Tab.document.getElementsByClassName('uniquename').innerHTML;
alert(Name);
</script>
</head>
</html>

You can use onLoad event in this case as:
var url = "www.website.com";
var Tab = window.open(url);
Tab.onload = function () {
var elems = Tab.document.getElementsByClassName('uniquename');
elems.forEach(function(elem,index){
console.log(elem)
})
};
But your URL in the child window should be in same domain.

Related

App Script - Open Url in new Tab from Google WebApp (without assigned Spreadsheet)

I want to create a WebApp, that does the following:
User clicks button on WebApp to run script
Get User eMail
Create new Google Spreadsheet (name=eMail)
get Url of that Spreadsheet
Automatically open Url in new Tab
Step 5 is where I am stuck.
I have used window.open(url) before, however that only seems to work when you run code via a Spreadsheet. What I wanna do is displaying the button on my .html and run everything only with the WebApp but I can't do that because I can not use SpreadsheetApp.getUi() from that context.
Is there another way to do this?
Here is the Error im getting:
EDIT: Seems I had some minor mistakes in my Code.gs I think i fixed that now. Still same issue tho
Thank you guys in advance! :)
Here is some sample code:
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("page");
}
function clickEvent () {
const lock = LockService.getScriptLock();
lock.tryLock(5000);
if (lock.hasLock()){
var email = Session.getActiveUser().getEmail();
var url = createFile(email);
openUrl(url); //THIS ONLY WORKED FROM WITHIN SPREADSHEET
lock.releaseLock();
}
}
function createFile(email){
var newSS= SpreadsheetApp.create(email);
var file = DriveApp.getFileById(newSS.getId());
var url = file.getUrl();
return url
}
function openUrl( url ){ //HAS TO CHANGE
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
}
}
page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Click Button!</h1>
<button id="btn">Run</button>
<script>
document.getElementById("btn").addEventListener("click",sendRequest);
function sendRequest(){
google.script.run.clickEvent();
}
</script>
</body>
</html>
Get url from app script and open spreadsheet in new tab wit JavaScript
Update app script function
function clickEvent () {
const lock = LockService.getScriptLock();
lock.tryLock(5000);
if (lock.hasLock()){
var email = Session.getActiveUser().getEmail();
lock.releaseLock();
return createFile(email);
}
}
Also update JavaScript Code
function sendRequest(){
google.script.run.withSuccessHandler(
function (link) {
window.open(link, '_blank').focus();
}
).testCSV3();
}
Reference: Communicate with Server Functions

How to retrieve the URL of the curent remote script?

Here is my page:
<html>
<head>
<script src = "//myremoteserver.com/chat.js"></script>
<script>
var chat = new Chat();
</script>
How can I retrieve the url of the script inside the Chat class?
(answer : //myremoteserver.com/chat.js)
I tried:
window.location.origin; gives me the url of the current page
document.getElementsByTagName('script') : do not provide url
You can access it by going through <head>.
document.getElementsByTagName("head")[0].getElementsByTagName("script")[0].src
You could give the script an id
<script id = "myScript" src = "//myremoteserver.com/chat.js"></script>
var element = document.getElementById('myScript');
console.log(element.src);
Can't see any reason why that wouldn't work.
Here is 2 ways to do this :
console.log(document.getElementsByTagName('script')[1].getAttribute("src"));
console.log(document.scripts[1].src);
<script src= "http://xxxxxxxxxxxxxxxxxxx"></script>

Javascript redirect not working if i delete alert

I have a function to redirect the page.
Function works perfectly when I have code like this.
document.getElementById("orderNow").addEventListener("click", function() {
// window.location.href = "http://www.w3schools.com", "_blank";
var name = document.getElementById("customerName").textContent;
var address = document.getElementById("customerStreet").textContent;
var city = document.getElementById("customerCity").textContent;
var state = document.getElementById("customerState").textContent;
var zip = document.getElementById("customerPcode").textContent;
var country = document.getElementById("customerCountry").textContent;
var phone = document.getElementById("customerPhone").textContent;
window.location.href = "https://www.amazon.com/gp/buy/addressselect/handlers/display.html?hasWorkingJavascript=1";
var username = document.getElementById('enterAddressFullName');
alert(username);
But if delete alert function or this:
var username = document.getElementById('enterAddressFullName');
Redirect won't work!
I don't know how to name the problem but this is my problem.
I don't want those last two lines of code. Help me to fix
Created a basic click event example for you below.
let orderButtonEl = document.getElementById("orderNow").addEventListener("click", function() {
// ... get all the values you need here and then do the redirect below
alert("Click Event Working!!");
// Redirect
window.location.href = "https://www.amazon.com/gp/buy/addressselect/handlers/display.html?hasWorkingJavascript=1";
});
<button id="orderNow"> Order Now </button>
EDIT:
Not sure what you are doing, but copy the following and save it as an index.html file. Open it with chrome, click on the button and it will redirect you.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id="orderNow">
Order Now
</button>
<script type="text/javascript">
let orderButtonEl = document.getElementById("orderNow").addEventListener("click", function() {
// ... do stuff
// Redirect
window.location.href = "https://www.amazon.com/gp/buy/addressselect/handlers/display.html?hasWorkingJavascript=1";
});
</script>
</body>
</html>

How to populate data and control when window.open

For example right, Google website.
I had found that Search textbox is name=q and Search button is name=btnK.
I am managed to open the browser by using the
var wdw = window.open(url, "_blank");
But I can't populate the data into the textbox as well as trigger the button.
I have tried like
wdw.document.getElementsByName("q").value = "something";
But still failed, please kindly advise. Thanks
2nd Attempt
var vWindow = window.open(GOOGLE_SITE, "_blank");
vWindow.onload = function() {
vWindow.document.getElementsByName("q").value = "Find ABC";
}
You meet the problem of security. Protocol, domain, etc
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
Another approach:
<!DOCTYPE html>
<html>
<body>
<button onclick="openNewWindow()">Open window</button>
<script>
function openNewWindow() {
// Open new window
var newWindow = window.open("", "My New Window", "width=500,height=500");
newWindow.document.write("<p>My New Widown</p>");
newWindow.document.write("<input type='text' id='name' />");
newWindow.document.write("<button id='ok'>OK</button>");
// populate the data into the textbox
newWindow.document.getElementById('name').value = "Test";
// Listen button click event
var btn = newWindow.document.getElementById('ok');
btn.addEventListener('click', clickOk);
}
function clickOk(){
console.log("Ok Click");
}
</script>
</body>
</html>

Run Function in original page from window.open javascript

how can I run Function in original page from window.open
original_page.html
<div id="Processing" style="display:none;">
<button onclick="window.open("Processing_window.html")">open</button>
</div>
<script language="JavaScript">
function submit_form() {
var upgradeForm = document.getElementById('upgradeForm');
setTimeout("upgradeForm.submit()",3000);
}
</script>
========
Processing_window.html
<script language="JavaScript">
function Processing_window() {
var doc = window.opener.document, Processing = doc.getElementById("Processing");
Processing.style = '';
submit_form(); //Here the problem
window.close();
}
setTimeout ("Processing_window()",5000);
</script>
========
I went to run "submit_form();" funcion from Processing_window.html
To access functions from the opener, use window.opener.functionName, assuming both are in the same domain.
function Processing_window() {
var doc = window.opener.document, Processing = doc.getElementById("Processing");
Processing.style = '';
// Here's the solution
window.opener.submit_form();
window.close();
}
setTimeout ("Processing_window()",5000);
You need to HTML encode the quotation marks in the code in the attribute, or use apostrophes:
<button onclick="window.open('Processing_window.html')">open</button>
As long as the page that you open has the same origin (same server, same protocol), you can use the opener property to access the parent windows window object. There's where you find the reference to the function:
window.opener.submit_form();
You can, but not cross-domain. Only in the same domain.
<script>
function new_win_fun() {
var wind = window.open("Processing_window.html");
var upgradeForm = wind.document.getElementById("upgradeForm");
wind.setTimeout("upgradeForm.submit()",3000);
}
</script>
<button onclick="new_win_func()">Run</button>

Categories