First of all, I am not a programmer. I do not know Javascript at all. I'm trying to create a Chrome extension that modifies my browser tab's title, by taking a specific string on a webpage. I know how to create Chrome extensions (just barely) and I just need to modify the Javascript to do what I want (which I do not know how).
I found the following script online and am trying to modify it but can't figure out how to get it working. Here is the script:
https://pastebin.com/dY1LSdjT
// Fire this event any time the mouse is moving. Sucks for performance, but it's a better experience
document.addEventListener("mousemove", function() {
// This will get us the banner
let bannerTextElements = document.getElementsByClassName("dijitReset dijitInputField dijitInputContainer");
console.log(bannerTextElements);
console.log(bannerTextElements[0]);
if (bannerTextElements[0]) {
console.log("ok!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(bannerTextElements[0].innerHTML);
// This will get us the text
let bannerTextLine = bannerTextElements[0].getElementsByClassName("dijitReset dijitInputInner");
console.log(bannerTextLine);
document.title = bannerTextLine[0].innerHTML
}
}, false);
And here's the website viewed in developer mode. I would like to get the text "blahhhh" and use that for the title of my browser tab.
Below is a different webpage and the difference here is that the "div class" names will change. The numbers in those class will change to different numbers, but the structure and the overall name remains the same. For example, "ms-Button-label label-549" may change to "ms-Button-label label-640". This happens whenever you refresh the page. I found that the "viewport" id name doesn't change though, so I think if we can use that as a reference and then just look at the nested div classes and reference them and extract the value (in this case Crystal Mountain).
Fixing your code
You got like 95% of everything you need.
The one thing you are missing right now is that the fact that an input element does not posses an "innerHTML" (That is why it isn't closed like this: <input>renderedText</input>). Instead you want to check for it's value:
document.title = bannerTextLine[0].value;
Some Improvements:
Search by ID
You have a well defined input which can be more easily obtained by looking it up using the id:
let bannerTextLine = document.getElementById('lanDeviceIndex_searchBox');
End result:
const bannerTextLine = document.getElementById('lanDeviceIndex_searchBox');
bannerTextLine.addEventListener("blur", function() {
if (bannerTextLine != null) {
document.title = bannerTextLine.value;
}
});
This is the entire JS code. Note that I changed the event to blur which activates when the form is left, this should be optimal for your case.
I'm using two simple addEventListener mouseenter and mouseleave functions respectively to play and stop animations (Bodymovin/SVG animations, though I suspect that fact is irrelevant).
So, the following works fine:
document.getElementById('animationDiv').addEventListener('mouseenter', function(){
animation.play();
})
(The HTML couldn't be simpler: The relevant part is just an empty div placeholder filled by script - i.e., <div id="animationDiv"></div>.
I can place that in the same file as the one that operationalizes the animation code, or I can place it in a separate "trigger" file, with both files (and other others necessary to processing) loaded in the site footer.
The problem arises when I need to be able to set triggers for any of multiple similar animations that may or may not appear on a given page.
If only one of two animatable elements are present on a page, then one of two sets of triggers will throw an error. If the first of two such triggers is not present, then the second one will not be processed, meaning that the animation will fail. Or at least that's what it looks like to me is happening.
So, just to be clear, if I add the following two triggers for the same page, and the first of the following two elements is present, then the animation will play on mouseenter. If only the second is present, its animation won't be triggered, apparently because of the error thrown on the first.
document.getElementById('firstAnimationDiv').addEventListener('mouseenter', function(){
firstAnimation.play();
})
document.getElementById('secondAnimationDiv').addEventListener('mouseenter', function(){
secondAnimation.play();
})
At present I can work around the problem by creating multiple trigger files, one for each animation, and setting them to load only when I know that the animatable element will be present, but this approach would get increasingly inefficient when I am using multiple animations per page, on pages whose content may be altered.
I've looked at try/catch approaches and also at event delegation approaches, but so far they seem a bit complicated for handling this simple problem, if appropriate at all.
Is there an efficient and flexible standard method for preventing or properly handling an error for an element not found, in such a way that subsequent functions can still be processed? Or am I missing something else or somehow misreading the error and the function failure I've been encountering?
WHY I PICKED THE ANSWER THAT I DID (PLUS WORKING CODE)
I was easily able to make the simple, directly responsive answer by Baoo work.
I was unable to make the answers below by Patrick Roberts and Crazy Train work, though no doubt my undeveloped js skills are entirely at fault. When I have the time, or when the issue next comes up for me in a more complex implementation (possibly soon!), I'll take another look at their solutions, and see if I can either make them work or if I can formulate a better question with fully fledged coding examples to be worked through.
Finally, just to make things clear for people who might be looking for an answer on Bodymovin animations, and whose js is even weaker than mine, the following is working code, all added to the same single file in which a larger set of Bodymovin animations are constructed, relieving me of any need to create separate trigger files, and preventing TypeErrors and impaired functionality.
//There are three "lets_talk" animations that can play - "home," "snug," and "fixed"
//and three types of buttons needing enter and leave play and stop triggers
let home = document.getElementById('myBtn_bm_home');
if (home) home.addEventListener('mouseenter', function() {
lets_talk_home.play();
});
if (home) home.addEventListener('mouseleave', function() {
lets_talk_home.stop();
});
let snug = document.getElementById('myBtn_bm_snug');
if (snug) snug.addEventListener('mouseenter', function() {
lets_talk_snug.play();
});
if (snug) snug.addEventListener('mouseleave', function() {
lets_talk_snug.stop();
});
let fixed = document.getElementById('myBtn_bm_fixed');
if (fixed) fixed.addEventListener('mouseenter', function() {
lets_talk_fixed.play();
});
if (fixed) fixed.addEventListener('mouseleave', function() {
lets_talk_fixed.stop();
});
At typical piece of underlying HTML (it's generated by a PHP function taking into account other conditions, so not identical for each button), looks like this at the moment - although I'll be paring away the data-attribute and class, since I'm not currently using either. I provide it on the off-chance that someone sees something significant or useful there.
<div id="letsTalk" class="lets-talk">
<a id="myBtn" href="#"><!-- a default-prevented link to a pop-up modal -->
<div class="bm-button" id="myBtn_bm_snug" data-animation="snug"></div><!-- "snug" (vs "fixed" or "home" is in both instances added by PHP -->
</a>
</div>
Obviously, a more parsimonious and flexible answer could be - and probably should be - written. On that note, correctly combining both the play and stop listeners within a single conditional would be an obvious first step, but I'm too much of a js plodder even to get that right on a first or second try. Maybe later/next time!
Thanks again to everyone who provided an answer. I won't ask you to try to squeeze the working solution into your suggested framework - but I won't ask you not to either...
Just write your code so that it won't throw an error if the element isn't present, by simply checking if the element exists.
let first = document.getElementById('firstAnimationDiv');
if (first) first.addEventListener('mouseenter', function() {firstAnimation.play();});
You could approach this slightly differently using delegated event handling. mouseover, unlike mouseenter, bubbles to its ancestor elements, so you could add a single event listener to an ancestor element where every #animationDiv is contained, and switch on event.target.id to call the correct play() method:
document.getElementById('animationDivContainer').addEventListener('mouseover', function (event) {
switch (event.target.id) {
case 'firstAnimationDiv':
return firstAnimation.play();
case 'secondAnimationDiv':
return secondAnimation.play();
// and so on
}
});
You could also avoid using id and use a more semantically correct attribute like data-animation as a compromise between this approach and #CrazyTrain's:
document.getElementById('animationDivContainer').addEventListener('mouseover', function (event) {
// assuming <div data-animation="...">
// instead of <div id="...">
switch (event.target.dataset.animation) {
case 'first':
return firstAnimation.play();
case 'second':
return secondAnimation.play();
// and so on
}
});
First, refactor your HTML to add a common class to all of the placeholder divs instead of using unique IDs. Also add a data-animation attribute to reference the desired animation.
<div class="animation" data-animation="first"></div>
<div class="animation" data-animation="second"></div>
The data- attribute should have a value that targets the appropriate animation.
(As #PatrickRobers noted, the DOM selection can be based on the data-animation attribute, so the class isn't really needed.)
Since your animations are held as global variables, you can use the value of data-animation to look up that variable. However, it would be better if they weren't global, but were rather in a common object.
const animations = {
first: null, // your first animation
second: null, // your second animation
};
Then select the placeholder elements by class, and use the data attribute to see if the animation exists, and if so, play it.
const divs = document.querySelectorAll("div.animation");
divs.forEach(div => {
const anim = animations[div.dataset.animation];
if (anim) {
anim.play(); // Found the animation for this div, so play it
}
});
This way you're guaranteed only to work with placeholder divs that exist and animations that exist.
(And as noted above, selection using the data attribute can be done const divs = document.querySelectorAll("div[data-animation]"); so the class becomes unnecessary.)
jsBin available here
My current scenario is that I am building a Vue.js-based plugin for the TinyMCE Editor.
The plugin allows me to configure certain elements in the editor reactively, before saving them (which would $destroy() the instance, and keep the element's rendered HTML in the editor in a no-longer-modifiable state).
There are several situations while editing where a particular element is replaced in the content (e.g. switching to "View source" and back). This causes me to lose the connection between vm and the HTML Element.
Description of the problem:
Here is a jsBin with a depiction of the problem. When clicking on Replace Element, one of the elements that is bound to Vue is replaced with a clone of itself. At this moment, it stops being bound to the data.
What can I do (if anything) in this situation to restore the bindings?
I tried asking in the Gitter channel, and also looking at the Vue source code, but I did not find anything. I also tried doing:
var vueConfig = { /* ... */ };
vm = new Vue(vueConfig);
onExternalReplacement = function() {
vm.$destroy();
vm = new Vue(vueConfig);
}
But since the cloned element does not have any of the original Vue directives (e.g. :style), it doesn't really help at all.
Thank you!
note: a solution in either Selenium or API wrapper Splinter for Selenium is fine!
I have been having issues interacting with the iframes on Twitter.com using the Splinter API for Python.
For example,
with Browser('firefox', profile_preferences= proxySettings) as browser:
#...login and do other stuff here
browser.find_by_id('global-new-tweet-button').click()
this brings up a pop-up box to type in a tweet.
How do I interact with this new box using Splinter to:
1) fill in a message
2) click "tweet" (submit)
..programmatically of course.
I tried inspecting the element but it doesn't seem to be nested inside of an iframe however it targets an iframe. So I am not sure how to find/interact with the elements in this pop-up.
I tried manually typing in a message then clicking the tweet button programmatically:
browser.find_by_css('.btn.primary-btn.tweet-action.tweet-btn.js-tweet-btn').click()
..but I get the error:
ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
Stacktrace:
at fxdriver.preconditions.visible (file:///var/folders/z1/8rqrglqn2dj8_yj1z2fv5j700000gn/T/tmppRsJvd/extensions/fxdriver#googlecode.com/components/command-processor.js:10092)
at DelayedCommand.prototype.checkPreconditions_ (file:///var/folders/z1/8rqrglqn2dj8_yj1z2fv5j700000gn/T/tmppRsJvd/extensions/fxdriver#googlecode.com/components/command-processor.js:12644)
at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/z1/8rqrglqn2dj8_yj1z2fv5j700000gn/T/tmppRsJvd/extensions/fxdriver#googlecode.com/components/command-processor.js:12661)
at DelayedCommand.prototype.executeInternal_ (file:///var/folders/z1/8rqrglqn2dj8_yj1z2fv5j700000gn/T/tmppRsJvd/extensions/fxdriver#googlecode.com/components/command-processor.js:12666)
at DelayedCommand.prototype.execute/< (file:///var/folders/z1/8rqrglqn2dj8_yj1z2fv5j700000gn/T/tmppRsJvd/extensions/fxdriver#googlecode.com/components/command-processor.js:12608)
I strictly want to achieve my goal using Splinter so please do not offer alternatives, I know there are other ways.
Thank you in advance!
You primary problem seems to be that you are treating the results of browser.find_by_xxx as an element object, when in reality it is an element container object (i.e. a list of webdriver elements).
Writing to the field works for me if I reference the element explicitly:
In [51]: elems = browser.find_by_id('tweet-box-global')
In [52]: len(elems)
Out[52]: 1
In [53]: elems[0].fill("Splinter Example")
In [54]:
That will write "Splinter Example" into the field for me.
The button click is failing because your css path is returning a list of three elements, and you are implicitly clicking on the first, hidden element. In my testing, the element you actually want to click on is the second element in the list:
In [26]: elems = browser.find_by_css('.btn.primary-btn.tweet-action.tweet-btn.js-tweet-btn')
In [27]: len(elems)
Out[27]: 3
In [28]: elems[1].click()
In [29]:
When I explicitly click the second element it doesn't throw an error and the button is clicked.
If you add to the css path you can narrow the results to only the button in the visible modal:
In [42]: css_path = "div.modal-tweet-form-container button.btn.primary-btn"
In [43]: elems = browser.find_by_css(css_path)
In [44]: len(elems)
Out[44]: 1
In [45]: elems.click()
In [46]:
Note that no exception was thrown here.
I'm a total newbie to Onsen UI and I managed to make my first little app (static that is) with a few pages, popovers, lists, etc.
But when I try to add dynamic stuff in there, it does not want to cooperate.
When I click my side menu, it calls menu.setMainPage and in the callback I want to modify the content of the list (lets say iterate a JSON request and add a ons-list-item for each of them). However, they do not look styled with Onsen UI icing.
I guess it's because the menu.setMainPage has already parsed the ons-page and showed it in the browser.
Is there a way to do a load page, update the dom, and then pass it to be displayed?
I have a simila problem with an popover that contains a list. I want to add items in that list, but my jQuery append never work. Same reason I suppose.
Thanks!
Sounds like you're not running ons.compile() on the dynamic elements. The custom elements must be compiled after they've been added to the DOM to get the correct style and behavior.
I made a short example to illustrate it:
ons.bootstrap();
var addItem = function() {
var $myList = $("#my-list"),
$item = $("<ons-list-item>").text(Math.random());
$myList.append($item[0]);
ons.compile($item[0]);
};
If you attach the addItem function to a click handler you can add items dynamically to an <ons-list>.
This is a running example on codepen:
http://codepen.io/argelius/pen/gbxNEg