Reconnecting with more BQL
Similar to connecting a 3rd-party library, you can also reconnect back and execute more BrowserQL as well. BQL does this by generating a new unique URL to use for running more queries. You can take this URL, append your API-token to it, and run more query language.
This is particularly useful for cases like AI where you might want to run several queries as users interact with your platform, but you don't want to necessarily keep an open connection.
Reconnecting with BQL
Below are examples of running two BQL queries on the same browser, in various languages:
- Javascript
- Python
- Java
- C#
const url = 'https://example.com';
const token = 'YOUR_API_TOKEN_HERE';
const timeout = 5 * 60 * 1000;
const queryParams = new URLSearchParams({
timeout,
token,
}).toString();
const endpoint = `https://production-sfo.browserless.io/chromium/bql`;
const variables = { url };
const query = `
mutation Reconnect($url: String!) {
goto(url: $url, waitUntil: networkIdle) {
status
}
reconnect(timeout: 30000) {
BypassQEEndpoint
}
}
`;
const queryTwo = `
mutation GetText {
text {
text
}
}
`;
const bql = async (url, query, variables) => {
const data = await fetch(`${url}?${queryParams}`, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
query,
variables,
}),
});
if (!data.ok) {
throw new Error(`Non OK response: ${await data.text()}`);
}
return data.json();
};
try {
console.log(`Running BQL Query#1: ${url}`);
const first = await bql(endpoint, query, variables);
const BypassQEEndpoint = first.data.reconnect.BypassQEEndpoint;
console.log(`Running BQL Query#2: ${BypassQEEndpoint}`);
const second = await bql(BypassQEEndpoint, queryTwo);
console.log(`Got results: "${second.data.text.text}"`);
} catch (error) {
console.error(error);
}
import requests
url = "https://example.com"
token = "YOUR_API_TOKEN_HERE"
timeout = 5 * 60 * 1000
query_params = {
"timeout": timeout,
"token": token,
}
endpoint = "https://production-sfo.browserless.io/chromium/bql"
variables = {"url": url}
query_one = """
mutation Reconnect($url: String!) {
goto(url: $url, waitUntil: networkIdle) {
status
}
reconnect(timeout: 30000) {
BypassQEEndpoint
}
}
"""
query_two = """
mutation GetText {
text {
text
}
}
"""
def bql(endpoint_url, query, variables):
response = requests.post(
f"{endpoint_url}?timeout={query_params['timeout']}&token={query_params['token']}",
headers={"Content-Type": "application/json"},
json={"query": query, "variables": variables},
)
if not response.ok:
raise Exception(f"Non OK response: {response.text}")
return response.json()
try:
print(f"Running BQL Query#1: {url}")
first_response = bql(endpoint, query_one, variables)
browser_qle_endpoint = first_response["data"]["reconnect"]["BypassQEEndpoint"]
print(f"Running BQL Query#2: {browser_qle_endpoint}")
second_response = bql(browser_qle_endpoint, query_two, {})
print(f'Got results: "{second_response["data"]["text"]["text"]}"')
except Exception as error:
print(f"Error: {error}")
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class BrowserlessBQE {
public static void main(String[] args) {
String url = "https://example.com";
String token = "YOUR_API_TOKEN_HERE";
int timeout = 5 * 60 * 1000;
String endpoint = "https://production-sfo.browserless.io/chromium/bql";
String queryOne = """
mutation Reconnect($url: String!) {
goto(url: $url, waitUntil: networkIdle) {
status
}
reconnect(timeout: 30000) {
BypassQEEndpoint
}
}
""";
String queryTwo = """
mutation GetText {
text {
text
}
}
""";
JsonObject variables = new JsonObject();
variables.addProperty("url", url);
try {
System.out.println("Running BQL Query#1...");
JsonObject firstResponse = runBQE(endpoint, queryOne, variables, token, timeout);
String BypassQEEndpoint = firstResponse
.getAsJsonObject("data")
.getAsJsonObject("reconnect")
.get("BypassQEEndpoint")
.getAsString();
System.out.println("Running BQL Query#2...");
JsonObject secondResponse = runBQE(BypassQEEndpoint, queryTwo, new JsonObject(), token, timeout);
String text = secondResponse
.getAsJsonObject("data")
.getAsJsonObject("text")
.get("text")
.getAsString();
System.out.println("Got results: \"" + text + "\"");
} catch (Exception e) {
e.printStackTrace();
}
}
private static JsonObject runBQE(String endpoint, String query, JsonObject variables, String token, int timeout) throws Exception {
String queryParams = String.format("?timeout=%d&token=%s", timeout, token);
URL url = new URL(endpoint + queryParams);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
JsonObject payload = new JsonObject();
payload.addProperty("query", query);
payload.add("variables", variables);
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream())) {
writer.write(payload.toString());
writer.flush();
}
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Non OK response: " + connection.getResponseMessage());
}
return JsonParser.parseReader(new java.io.InputStreamReader(connection.getInputStream())).getAsJsonObject();
}
}
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
class Program
{
static void Main(string[] args)
{
string url = "https://example.com";
string token = "YOUR_API_TOKEN_HERE";
int timeout = 5 * 60 * 1000;
string endpoint = "https://production-sfo.browserless.io/chromium/bql";
string queryOne = @"
mutation Reconnect($url: String!) {
goto(url: $url, waitUntil: networkIdle) {
status
}
reconnect(timeout: 30000) {
BypassQEEndpoint
}
}
";
string queryTwo = @"
mutation GetText {
text {
text
}
}
";
var variables = new { url };
try
{
Console.WriteLine("Running BQL Query#1...");
var firstResponse = RunBQE(endpoint, queryOne, variables, token, timeout);
string BypassQEEndpoint = firstResponse
.GetProperty("data")
.GetProperty("reconnect")
.GetProperty("BypassQEEndpoint")
.GetString();
Console.WriteLine("Running BQL Query#2...");
var secondResponse = RunBQE(BypassQEEndpoint, queryTwo, new { }, token, timeout);
string text = secondResponse
.GetProperty("data")
.GetProperty("text")
.GetProperty("text")
.GetString();
Console.WriteLine($"Got results: \"{text}\"");
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {ex.Message}");
}
}
static JsonElement RunBQE(string endpoint, string query, object variables, string token, int timeout)
{
string queryParams = $"?timeout={timeout}&token={token}";
var url = endpoint + queryParams;
var payload = new
{
query,
variables
};
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonPayload = JsonSerializer.Serialize(payload);
streamWriter.Write(jsonPayload);
streamWriter.Flush();
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"Non OK response: {response.StatusDescription}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd();
return JsonSerializer.Deserialize<JsonElement>(result);
}
}
}
}