Webextension: how to wait for a specific element to appear in the page? - promise

I want to develop a content-script webextension for a particular website, whose document's scripts insert elements into the DOM. I would like my content-script wait for the elements to appear in the DOM so that it can interact with the elements.
I am thinking in line of the Page.WaitForSelector() method that is available in the Puppeteer node.js library. I would like to do something like the following:
const button = await waitForSelector('a[role="click-me"]');
button.click();
const purpose = await waitForSelector('input[data="purpose']');
purpose.innerText = "I want to dump my brain";
waitForSelector has a 2nd timeout parameter with a reasonable default value. It returns a promise which resolves to a HTMLelement when the element appears in the document.body or null on timeout. I would need to develop my webextension iteratively to find the correct selector strings for the waitForSelector's first parameter.
How do I implement waitForSelector?

Related

How to appendChild in the Wix Corvid/Code IDE

I've searched thru Corvid docs and Stack, not finding anything.
Is there a way to appendChild() in Wix Corvid(Code)?
EDIT: Wix does not allow DOM access directly. I assumed that people answering this would know i was looking for an alternative to appencChild and knew this method could not be used as is in Wix.
so to clarify: is there a way to add a child to a parent element using Wix's APIs?
It depends what you are trying to achieve,
the only thing off the top of my head is adding more items to a repeater
which you can do by first getting the initial data from the repeater, adding another item to array and reassign the data property of the repeater
const initialData = $w('#repeater').data
const newItem = {
_id: 'newItem1', // Must have an _id property
content: 'some content'
}
const newData = [...initialData, newItem]
$w('#repeater').data = newData
https://www.wix.com/corvid/reference/$w.Repeater.html#data
In Corvid, you cannot use any function which accesses the DOM.
Coming from one of the developers of Corvid:
Accessing document elements such as div, span, button, etc is off-limits. The way to access elements on the page is only through $w. One small exception is the $w.HtmlComponent (which is based on an iFrame). This element was designed to contain vanilla HTML and it works just fine. You just can't try to trick it by using parent, window, top, etc.
Javascript files can be added to your site's Public folder, but the same limitations apply - no access to the DOM.
Read more here: https://www.wix.com/corvid/forum/main/comment/5afd2dd4f89ea1001300319e

Can't parse html correctly / empty body after parsing

I am facing an odd problem. I im trying to parse the following html:
The problem is that when I do
response.xpath('//div//section//div[#id="hiring-candidate-app"]')[0].extract()
I only get
'<div id="hiring-candidate-app"></div>'
instead of all the content under hiring-candidate-app.
I would like to get, for instance, inside-content, but it looks like I am not even getting that in the response. This webpage requires to be logged in, which I am.
Thanks in advance!
It looks like your Xpath is grabbing the right thing. But your issue might have to do with the '[0]' part of the call. I would remove that to get the full content of the div.
It looks like the elements in question sit on an <iframe>, and therefore live in a different context. You need to activate or switch to the context of the iframe, eg. using JavaScript to interact with an iframe and the document inside of it, e.g.
//Note: Assigning document.domain is forbidden for sandboxed iframes, i.e. on stacksnippets
//document.domain = "https://stacksnippets.net";
var ifrm = document.getElementById("myFrame");
// reference to iframe's window
//var win = ifrm.contentWindow;
// reference to document in iframe
var doc = ifrm.contentDocument ? ifrm.contentDocument : ifrm.contentWindow.document;
// reference an element via css selector in iframe
//var form = doc.getElementById('body > div > div.message');
// reference an element via xpat in iframe
var xpathResult = doc.evaluate("/html/body/div/div[1]", doc, null, XPathResult.ANY_TYPE, null);
<iframe id="myFrame" src="https://stacksnippets.net" style="height:380px;width:100%"></iframe>
However, as you can see when you run the snipped, cross-document interactions are only possible if the documents have the same origin. There are other, more involved methods like the postMessage method that provide the means of interacting cross-domain.

jQuery 'on' not registering in dynamically generated modal popup

I was under the impression that jQuery's on event handler was meant to be able to 'listen' for dynamically created elements AND that it was supposed to replace the behavior of live. However, what I have experienced is that using on is not capturing the click event whereas using live is succeeding!
The tricky aspect of my situation is that I am not only dynamically creating content but I'm doing it via an AJAX .get() call, and inserting the resultant HTML into a modal .dialog() jQueryUI popup.
Here is a simplified version of what I was trying to accomplish (wrapped in $(document).ready(...) ):
$.get("getUserDataAjax.php", queryString, function(formToDisplay) {
$("#dialog").dialog({
autoOpen: true,
modal: true,
buttons...
}).html(formToDisplay);
});
$(".classThatExistsInFormToDisplay").on("click", function() {
alert("This doesn't get called");
});
From the documentation for on I found this which which was how I was approaching writing my on event:
$("p").on("click", function(){
alert( $(this).text() );
});
However, for some reason, live will work as I expect -- whereas on is failing me.
This isn't a question for "how can I make it work" because I have found that on will succeed (capture clicks) if I declare it inside the function(formToDisplay) callback.
My question is: what is wrong with on that it isn't finding my dynamically created elements within a modal popup? My jQuery instance is jquery-1.7.2. jQueryUI is 1.8.21.
Here are two jsFiddles that approximate the issue. Click the word "Test" in both instances to see the different behavior. The only difference in code is replacing on for live.
Where the click is captured by live.
Where the click is NOT captured by on (click 'Test - click me' to see nothing happen).
I realize I may just be using on inappropriately or asking it to do something that was not intended but I want to know why it is not working (but if you have something terribly clever, feel free to share). Thanks for your wisdom!
Update / Answer / Solution:
According to user 'undefined', the difference is that on is not delegated all the way from the top of the document object whereas live does/is.
As Claudio mentions, there are portions of the on documentation that reference dynamically created elements and that what you include in the $("") part of the query needs to exist at runtime.
Here is my new solution: Capture click events on my modal dialog, which, although it does not have any content when the event is created at runtime, will be able to find my content and element with special class that gets generated later.
$("#dialog").on("click", ".classThatExistsInFormToDisplay", function() {
... //(success! Event captured)
});
Thanks so much!
live delegates the event from document object, but on doesn't, if you want to delegate the event using on method, you should delegate the event from one of static parents of the element or document object:
$(document).on("click", ".clickHandle", function() {
alert("Content clicked");
});
The problem is that the element to which you attach the event has to exist.
You have to use on like this to capture clicks on p tags created dynamically
$("#existingContainerId").on("click", "p", function(){
alert( $(this).text() );
});
if you have no relevant existing container to use, you could use $("body") or $(document)
If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next
Take a look to section Direct and delegated events here for more details

JQuery Ajax - Rebinding elements with the context param instead of delegate?

So we all know in an ajax update events must be rebound to new dom elements. Yes delegate is an option, but delegate doesn't work for all scenarios. For instance delegate won't help for something that needs to be done simply on load rather than on a click event.
Rather than split my code into delegate handlers and handlers that need to be rebound on updates, I would rather define a single method with a context parameter that gets called every time the page changes like so:
function onPageUpdate(context) {
$('a', context).click(...); // event handlers
$('.chart', context).addClass(...); // load handlers
}
On dom ready this will be called with the context parameter null. On an ajax update the context will container the new dom elements. This way I'll never have to worry about delegating or ajax updates again.
I'm having trouble getting this to work however. Given the ajax callback:
function onSuccess(data) {
// data contains new dom elements like: <div><a>Click</a><span>chart<span></div>
// replace old elements with new ones
$('a').replaceWith('a', data);
$('span').replaceWith('span', data);
// call pageUpdate with the new context
onPageUpdate(data);
}
Is it possible to make this work like I expect? The replacing works fine, but onPageUpdate isn't binding anything to these new elements, I don't know if thats because the context is just a string object or what. Can anyone think of a way to make this work?
In my mind this is a better solution than delegate, because theres only one method for all handlers and only the elements that need a binding will own it.
From jQuery() - jQuery API
jQuery( selector [, context] )
selector A string containing a selector expression
context A DOM Element, Document, or jQuery to use as context
If the context isn't the correct type - such as passing a string - it's simply going to be ignored. Try wrapping your HTML string in a jQuery object, then use that as the context for your selectors, like so:
var $context = $(data);
$('a').replaceWith('a', $context);
$('span').replaceWith('span', $context);
// call pageUpdate with the new context
onPageUpdate($context);
I won't answer to your question, Anthony Grist's answer is quite right, but there are some things you said that I don't understand. Could you explain them to me ?
For instance delegate won't help for something that needs to be done simply on load rather than on a click event
Sorry but I don't get it, do you have an example ?
In my mind this is a better solution than delegate, because theres
only one method for all handlers and only the elements that need a
binding will own it.
I don't get it too:
only one method: which method are you talking about ?
only the elements ... will own it: it's also the case with delegate, and more, if you have let's say 10 anchor element, only ONE handler would be bound, instead of 10 in your solution
On your method onPageUpdate you're mixing two things: event handling ($("a").click(...)) and DOM modification ($(".char").addClass(...)). Maybe that's why you're confusing about delegate's ability to resolve your problem.

Google Chrome Extension - How can I include a content script more than once?

I've been working on Chrome Extension for a website for the past couple of days. It's coming along really nicely but I've encountered a problem that you might be able to help with.
Here's an outline of what the extension does (this functionality is complete):
A user can enter their username and password into the extensions popup - and verify their user account for the particular website
When a user browses http://twitter.com a content script is dynamically included that manipulates the DOM to include an extra button next to each tweet displayed.
When a user clicks this button they are presented with a dialog box
I've made a lot of progress but here is my problem:
When a user visits Twitter the content script is activated and all tweets on the page get my new button - but if the user then clicks 'More...' and dynamically loads the next 20 tweets... these new additions to the page DOM do not get affected by the content script (because it is already loaded).
I could add an event listener to the 'More...' button so it then triggers the original content script again (and adds the new button) but i would have to predict the length of twitter's ajax request response.
I can't tap into their Ajax request that pulls in more tweets and call my addCurateButton() function once the request is complete.
What do you think is the best solution? (if there is one)
What you want to do is to re-execute your content-script every time the DOM is changed. Luckily there is an event for that. Have a look at the mutation event called DOMNodeInserted.
Rewrite your content script so that it attaches an event listener to the body of the DOM for the DOMNodeInserted event. See the example below:
var isActive = false;
/* Your function that injects your buttons */
var inject = function() {
if (isActive) {
console.log('INFO: Injection already active');
return;
}
try {
isActive = true;
//inject your buttons here
//for the sake of the example I just put an alert here.
alert("Hello. The DOM just changed.");
} catch(e) {
console.error("ERROR: " + e.toString());
} finally {
isActive = false;
}
};
document.body.addEventListener("DOMNodeInserted", inject, false);
The last line will add the event listener. When a page loads the event is triggered quite often so you should define a boolean (e.g. var isActive), that you initialize to false. Whenever the inject function is run check whether isActive == true and then abort the injection to not execute it too often at the same time.
Interacting with Ajax is probably the hardest thing to coax a content script to do, but I think you’re on the right track. There are a couple different approaches I’ve taken to solving this problem. In your case, though, I think a combination of the two approaches (which I’ll explain last) would be best.
Attach event listeners to the DOM to detect relevant changes. This solution is what you’ve suggested and introduces the race condition.
Continuously inspect the DOM for changes from inside a loop (preferably one executed with setInterval). This solution would be effective, but relatively inefficient.
The best-of-both-worlds approach would be to initiate the inspection loop only after the more button is pressed. This solution would both avoid the timing issue and be efficient.
You can attach an event-handler on the button, or link that is used for fetching more results. Then attach a function to it such that whenever the button is clicked, your extension removes all the buttons from DOM and starts over inserting them, or check weather your button exists in that particular class of DOM element or not and attach a button if it doesn't.

Resources