Click on element in Electron webview - javascript

I want to click an element (button) several times in a remote website loaded through webview in Electron.
The following works when I enter it in the console (via inspect element):
a = setInterval( function(){
var elem = document.getElementsByClassName("myclass");
elem[0].click()
},1000)
It doesn't when I use it in Electron main script:
window.webContents.executeJavaScript('a = setInterval( function(){ var elem = document.getElementsByClassName("myclass"); elem[0].click() },1000)', true);
I get an error:
Uncaught TypeError: Cannot read property 'click' of undefined at :1:110
I also tried the scipt preloaded in webview tag, but no luck.
What am I missing, or doing wrong?
chromiumVersion: "58.0.3029.110"
electronVersion: "1.7.9"
nodeVersion:"7.9.0"
EDIT
Testing with Google.com and the speech icon in the searchbar:
var element = document.getElementsByClassName('gsst_a');
if (typeof(element) != 'undefined' && element != null) {
console.log('yep, element is found');
console.log(element);
console.log(element[0]);
a = setInterval(
function(){
var elem = document.getElementsByClassName("gsst_a");
elem[0].click()
},1000)
} else {
console.log('nope, element is not found');
}
This clicks the icon every 1 second in Chrome when entered in console.
When I have my webview set to Google.com and have the following line, it still finds the element, but gives the error mentioned earlier again:
window.webContents.executeJavaScript('var element=document.getElementsByClassName("gsst_a");void 0!==element&&null!=element?(console.log("yep, element is found"),console.log(element),console.log(element[0]),a=setInterval(function(){document.getElementsByClassName("gsst_a")[0].click()},1e3)):console.log("nope, element is not found");', true);
console.log(element) gives: HTMLCollection(0)
console.log(element[0]) gives: undefined
Why can I enter the js in my normal browser, but not in Electron webview?

To answer my own question.
The event's referring to the web page in the BrowserWindow, not the webview within that. So the element doesn't exist in the scope I was looking in, and I needed to do something similar within the BrowserWindow.
Code:
<html>
<head>
<style type="text/css">
* { margin: 0; }
#browserGoogle { height: 100%; }
</style>
</head>
<body>
<webview id="browserGoogle" src="https://google.com"></webview>
<script>
const browserView = document.getElementById('browserGoogle')
browserView.addEventListener('dom-ready', () => {
const browser = browserView.getWebContents()
browser.setDevToolsWebContents(devtoolsView.getWebContents())
browser.webContents.executeJavaScript('var element=document.getElementsByClassName("gsst_a");void 0!==element&&null!=element?(console.log("yep, element is found"),console.log(element),console.log(element[0]),a=setInterval(function(){document.getElementsByClassName("gsst_a")[0].click()},1e3)):console.log("nope, element is not found");', true);
})
</script>
</body>
</html>

Related

How to select/hide elements inside an object of type "text/html" using javascript [duplicate]

I'm using the object tag to load an html snippet within an html page.
My code looks something along these lines:
<html><object data="/html_template"></object></html>
As expected after the page is loaded some elements are added between the object tags.
I want to get those elements but I can't seem to access them.
I've tried the following
$("object").html() $("object").children() $("object")[0].innerHTML
None of these seem to work. Is there another way to get those elements?
EDIT:
A more detailed example:
consider this
<html><object data="http://www.YouTube.com/v/GGT8ZCTBoBA?fs=1&hl=en_US"></object></html>
If I try to get the html within the object I get an empty string.
http://jsfiddle.net/wwrbJ/1/
As long as you place it on the same domain you can do the following:
HTML
<html>
<object id="t" data="/html_template" type="text/html">
</object>
</html>
JavaScript
var t=document.querySelector("#t");
var htmlDocument= t.contentDocument;
Since the question is slightly unclear about whether it is also about elements, not just about the whole innerHTML: you can show element values that you know or guess with:
console.log(htmlDocument.data);
The innerHTML will provide access to the html which is in between the <object> and </object>. What is asked is how to get the html that was loaded by the object and inside the window/frame that it is producing (it has nothing to do with the code between the open and close tags).
I'm also looking for an answer to this and I'm afraid there is none. If I find one, I'll come back and post it here, but I'm looking (and not alone) for a lot of time now.
No , it's not possible to get access to a cross-origin frame !
Try this:
// wait until object loads
$('object').load(function() {
// find the element needed
page = $('object').contents().find('div');
// alert to check
alert(page.html());
});
I know this is an old question, but here goes ...
I used this on a personal website and eventually implemented it in some work projects, but this is how I hook into an svg's dom. Note that you need to run this after the object tag has loaded (so you can trigger it with an onload function). It may require adaptation for non-svg elements.
function hooksvg(elementID) { //Hook in the contentDocument of the svg so we can fire its internal scripts
var svgdoc, svgwin, returnvalue = false;
var object = (typeof elementID === 'string' ? document.getElementById(elementID) : elementID);
if (object && object.contentDocument) {
svgdoc = object.contentDocument;
}
else {
if (typeof object.getSVGDocument == _f) {
try {
svgdoc = object.getSVGDocument();
} catch (exception) {
//console.log('Neither the HTMLObjectElement nor the GetSVGDocument interface are implemented');
}
}
}
if (svgdoc && svgdoc.defaultView) {
svgwin = svgdoc.defaultView;
}
else if (object.window) {
svgwin = object.window;
}
else {
if (typeof object.getWindow == _f) {
try {
svgwin = object.getWindow();//TODO look at fixing this
}
catch (exception) {
// console.log('The DocumentView interface is not supported\r\n Non-W3C methods of obtaining "window" also failed');
}
}
}
//console.log('svgdoc is ' + svgdoc + ' and svgwin is ' + svgwin);
if (typeof svgwin === _u || typeof svgwin === null) {
returnvalue = null;
} else {
returnvalue = svgwin;
}
return returnvalue;
};
If you wanted to grab the symbol elements from the dom for the svg, your onload function could look like this:
function loadedsvg(){
var svg = hooksvg('mysvgid');
var symbols = svg.document.getElementsByTagName('symbol');
}
You could use the following code to read object data once its loaded completely and is of the same domain:
HTML-
<html>
<div class="main">
<object data="/html_template">
</object>
</div>
</html>
Jquery-
$('.main object').load(function() {
var obj = $('.main object')[0].contentDocument.children;
console.log(obj);
});
Hope this helps!
Here goes a sample piece of code which works. Not sure what the problem is with your code.
<html>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var k = $("object")[0].innerHTML;
alert(k);
$("object")[0].innerHTML = "testing";
});
</script>
<object data="/html_template">hi</object>
</html>
UPDATED
I used this line of Javascript to change the value of a input filed inside an iFrame, taken from How to pick element inside iframe using document.getElementById:
document.getElementById('iframeID').contentWindow.document.getElementById('inputID').value = 'Your Value';
In your case, since you do not have a frame, and since you want to get and not set the value, log it for example with:
console.log(document.getElementById('object').value);
And if you guess or choose an element:
console.log(document.getElementById('object').data);

where is showing conversation value

THis topic is abouton google add word (conversation)
Below is my conversation setup screenshot
http://nimb.ws/alycTQ
Below is my code that was putted on body tag
<script type="text/javascript">
/* <![CDATA[ */
function GoogleFormTracker()
{
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = 949468534;
w.google_conversion_label = "9xLwCK7rm3IQ9vrexAM";
w.google_conversion_value = 1;
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
GoogleFormTracker() fired on footer when site is load.
And also i verified my code on tag manager chrome addons(No error showing there).
but i don't know where to showing me how many time this function is fired ?
let me know any mistake in my code or where is showing tracking value in add word (with screenshot and step by step).
Thanks
In google add word account follow below step
Tool->Attribution
In Attribution available you conversation value.
I hope u need like above
"but i don't know where to showing me how many time this function is fired". Not entirely sure I understand, but perhaps you just need to put a console.log('marco'); inside the function and view the browser console (ctrl + shift + i) to see how many times the function is called?

Safari print with Javascript produces blank when printing an Iframe

I have read up on all issues regarding Safari and blank printing. It seems that a white flash happens, re-rendering the page, and content of the iframe is lost before a print dialog can grab it.
Here is my javascript - It works in all browsers except safari. It brings up the dialog, but prints a blank page.
function PrintPopupCode(id) {
framedoc = document;
var popupFrame = $(framedoc).find("#" + id + '\\!PopupFrame');
var icontentWindow = popupFrame[0].contentWindow || popupFrame[0].contentDocument;
icontentWindow.focus();
icontentWindow.print();
}
function PrintPopup(id) {
setTimeout(function () { PrintPopupCode(id) }, 3000);
}
I have set a timeout, i previously read it would help if the transfer of content took sometime, but it has not helped.
I have also tried with printElement() function on the icontentWindow variable, but it does not support this method.
Print Element Method
This is all in a .js file, and not on the page. I have tried on the page, but the same thing happens.
Help?
Maybe you should try this:
function PrintPopupCode(id) {
framedoc = document;
var popupFrame = $(framedoc).find("#" + id + '\\!PopupFrame');
var icontentWindow = popupFrame[0].contentWindow || popupFrame[0].contentDocument;
icontentWindow.focus();
setTimeout(icontentWindow.print, 3000);
}
function PrintPopup(id) {
PrintPopupCode(id);
}

Javascript document.title doesn't work in Safari

I'm using Safari 6.0.5.
I open a new empty window, try to change the title to 'debug window', nothing happens. With a check function checking every 10 milliseconds, it says the window.document.title is 'Debug Window', still the new Window title bar says it is 'untitled'.
var debug_window = window.open('', 'debug_window', 'height=200');
debug_window.document.title = 'Debug Window';
function check()
{
debugLog(1, 'title:' + debug_window.document.title);
if(debug_window.document) { // if loaded
debug_window.document.title = "debug_window"; // set title
} else { // if not loaded yet
setTimeout(check, 10); // check in another 10ms
}
}
check();
The output in the debugLog is:
17:35:04.558: title:
17:35:04.584: title:debug_window
What is going wrong here that the new window is still called 'untitled'?
Thanks!
Now the second argument to window.open() is a frame/window-name and serves also as the default title. This is eventually overridden by the document loaded into this window. Opening the document-stream and inserting a basic html-document should serve the purpose:
var debug_window = window.open('', 'debug_window', 'height=200');
debug_window.document.open();
debug_window.document.write('<!DOCTYPE html>\n<html lang="en">\n<head>\n<title>Debug Window</title>\n</head>\n<body></body>\n</html>');
debug_window.document.close();
var debug_body = debug_window.document.getElementsByTagName('body')[0];
// write to debug_window
debug_body.innerHTML = '<p>Message</p>';
So you would be setting up a basic document inside the window, just as it would be loaded by the server (by writing to the "document stream"). Then you would start to manipulate this document like any other.
Edit: Does not work in Safari either.
Other suggestion: set up a basic document (including the title) on the server and inject the content into its body on load. As a bonus, you may setup CSS via stylesheets.
var debug_window = window.open('debug_template.html', 'debug_window', 'height=200');
debug_window.onload = function() {
var debug_body = debug_window.document.getElementsByTagName('body')[0];
debug_body.innerHTML = '...';
// or
// var el = document.createElement('p');
// p.innerHTML = '...';
// debug_body.appendChild(p);
debug_window.onload=null; // clean up cross-reference
};
And on the server side something like
<!DOCTYPE html>
<html lang="en">
<head>
<title>Debug Window</title>
<link rel="stylesheet" href="debug_styles.css" type="text/css" />
</head>
<body></body>
</html>
If this still should not work (e.g.: writing to the debug-window's document is without effect), you could call your app from inside the debug-window by something like:
<body onload="if (window.opener && !window.opener.closed) window.opener.debugCallback(window, window.document);">
</body>
(So you would check if the opener – your App – exists and hasn't been closed in the meantime and then call a callback-function "debugCallback()" in your app with the debug-window and its document as arguments.)
Try:
var debug_window = window.open('about:blank', 'debug_window', 'height=200');

jQuery change page's title when user in a different tab

I have live chat on my page. I want to change the title (with something moving like in omegle.com) when a new message is received and the user is not in the same tab as the live chat. When the user returns to the tab, the title would return to normal.
I guess it should be done by jQuery. Do you know any plugins or how can I do that?
Title can only be edited like so:
document.title = "blah";
So you could do:
var origTitle = document.title;
document.title = "You have ("+x+") new messages - "+origTitle;
To make it flash you would have to do something with setTimeout();
var origTitle = document.title;
var isChatTab = false; // Set to true/false by separate DOM event.
var animStep = true;
var animateTitle = function() {
if (isChatTab) {
if (animStep) {
document.title = "You have ("+x+") new messages - "+origTitle;
} else {
document.title = origTitle;
}
animStep = !animStep;
} else {
document.title = origTitle;
animStep = false;
}
setTimeout(animateTitle, 5000);
};
animateTitle();
try
$('title').text("some text");
Update
Apparantly, in IE, $('title')[0].innerHTML returns the content of the <title> tag, but you can't set it's value, except using document.title. I guess this should be an improvement to the jQuery API, since $('title')[0] does return a DOMElement (nodeType = 1)...
$('title').text('your title') suffices.
To see if you're taking the right path, simply use IE's developer toolbar (F12) and go to console and write $('title'), you should see [...] in console. This means that $('title') is an object and it works up to here. Then write typeof $('title').text, and you should see function as the result. If these tests are OK, then your IE is broken.

Categories