Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dispatch input and change events at the chromedp.SetValue target #819

Merged
merged 1 commit into from May 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion js.go
Expand Up @@ -78,7 +78,12 @@ const (
// setAttributeJS is a javascript snippet that sets the value of the specified
// node, and returns the value.
setAttributeJS = `(function(a, n, v) {
return a[n] = v;
a[n] = v;
if (n === 'value') {
a.dispatchEvent(new Event('input', { bubbles: true }));
a.dispatchEvent(new Event('change', { bubbles: true }));
}
return a[n];
})(%s, %q, %q)`

// visibleJS is a javascript snippet that returns true or false depending on if
Expand Down
16 changes: 16 additions & 0 deletions query_test.go
Expand Up @@ -2,6 +2,8 @@ package chromedp

import (
"bytes"
"context"
"errors"
"fmt"
"image/png"
"io/ioutil"
Expand Down Expand Up @@ -557,6 +559,7 @@ func TestSetValue(t *testing.T) {
{`#form > input[type="text"]`, ByQueryAll},
{`#bar`, ByID},
{`document.querySelector("#bar")`, ByJSPath},
{`#select`, ByQuery},
}

for i, test := range tests {
Expand All @@ -578,6 +581,19 @@ func TestSetValue(t *testing.T) {
if value != "FOOBAR" {
t.Errorf("expected `FOOBAR`, got: %s", value)
}

ctx, cancel = context.WithTimeout(ctx, 2*time.Second)
defer cancel()
if err := Run(ctx,
WaitVisible("#event-input", ByQuery),
WaitVisible("#event-change", ByQuery),
); err != nil {
if errors.Is(err, context.DeadlineExceeded) {
t.Fatal("input and/or change events not fired")
} else {
t.Fatalf("got error: %v", err)
}
}
})
}
}
Expand Down
14 changes: 14 additions & 0 deletions testdata/form.html
Expand Up @@ -16,8 +16,22 @@
<textarea id="bar" rows="4" cols="50">bar</textarea><br>
<input id="btn1" name="reset" type="reset" value="Reset">
<input id="btn2" name="submit" type="submit" value="Submit">
<select id="select">
<option value="">First</option>
<option value="FOOBAR">Second</option>
</select>
<p id="inner-hidden">this is <span style="display: none;">hidden</span></p>
<p id="hidden" style="display: none;">hidden</p>
</form>
<span id="event-input" style="display: none">input event fired</span>
<span id="event-change" style="display: none">change event fired</span>
<script>
document.addEventListener('input', ()=>{
document.getElementById('event-input').style.display = 'block';
})
document.addEventListener('change', ()=>{
document.getElementById('event-change').style.display = 'block';
})
</script>
</body>
</html>