beforeunload event on page refresh in firefox - javascript

I am currently using faye for pubsub and am disconnecting the client on the beforeunload event.While it disconnects during tab close during page refresh it throws the following error :
The connection was interrupted while the page was loading
The code is
window.addEventListener('beforeunload',function(event){
fayeClient.disconnect();
event.preventDefault();});
Is there a way to stop firefox from closing the connection before the call completes.The above code works perfectly in chrome

How can I prevent a page unload with jQuery?
way down in the comments it says:
event.preventDefault() doesn't work in this case, presumably because modern browsers don't want malicious coders to hijack the window and make it un-closable? – yochannah May 9 '13 at 8:45
I dont believe it is possible to delay it longer then it takes for that code to execute, excluding any async returns and timeouts.
So, to hack this. Call your disconnect, then make a synchronous call to a file which does
<?php
sleep(1);

Related

Selenium-js: Firefox: Error: TimedPromise timed out after 300000 ms

I am trying to run my selenium javascript on the site bet365.com. I am using Firefox (geckodriver), I tried both headless and normal but for understanding/debugging the problem the non-headless-mode is helpful.
This is the code:
const driver = await new Builder().forBrowser("firefox").build();
await driver.get("https://bet365.com");
The problem is that the site is not loading:
After 5 mins I then end up with the error
TimeoutError: TimedPromise timed out after 300000 ms
at Object.throwDecodedError (C:\1_code\RFB\git\webscraper-srv\node_modules\selenium-webdriver\lib\error.js:517:15)
at parseHttpResponse (C:\1_code\RFB\git\webscraper-srv\node_modules\selenium-webdriver\lib\http.js:671:13)
at Executor.execute (C:\1_code\RFB\git\webscraper-srv\node_modules\selenium-webdriver\lib\http.js:597:28)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Driver.execute (C:\1_code\RFB\git\webscraper-srv\node_modules\selenium-webdriver\lib\webdriver.js:729:17)
at async C:\1_code\RFB\git\webscraper-srv\scripts\seleniumUtils.js:190:3
at async XWrap.<anonymous> (C:\1_code\RFB\git\webscraper-srv\scripts\utils.js:127:60)
at async XWrap.<anonymous> (C:\1_code\RFB\git\webscraper-srv\scripts\utils.js:127:60)
at async XWrap.<anonymous> (C:\1_code\RFB\git\webscraper-srv\scripts\utils.js:127:60)
at async XWrap.<anonymous> (C:\1_code\RFB\git\webscraper-srv\scripts\utils.js:127:60) {
remoteStacktrace: 'WebDriverError#chrome://marionette/content/error.js:181:5\n' +
'TimeoutError#chrome://marionette/content/error.js:450:5\n' +
'bail#chrome://marionette/content/sync.js:229:19\n'
I tried visiting a different site with selenium and they work perfectly so I don't think its a problem with my setup.
If I try visiting the site with my normal Firefox Browser it works too.
I also tried manually searching for the page in the browser which is opened by the program and it leads to another endless loop. But manually opening other pages in this browser opened by selenium works fine.
Is it possible for the server of a webpage to detect browsers that were started using selenium? I always thought the only way to detect webscrapers was by looking at the frequency it is visiting and the clicks the scraper is doing on a page but it is the first time I visited the page with Selenium...
If the server doesn't allow these kind of requests, is there any way to still scrape data from this webpage? I also already tried opening it in headless mode...
This is the (entire) Firefox Network tab when its stuck loading (sometimes it looks a little different):
This is the (begin of the) Firefox Network tab when its loaded normally:
I circled the requests that might be causing the problem. In the bottom left of the browser it's telling me the entire time that it's Transfering data from ff.kis.v2.scr.kaspersky-labs.com. I tried deactivating kaspersky on my machine and also let the progamme run on a machine without kaspersky so I am not quite sure why this request is made. It might have to do something with https validation but I am not sure.
Another interesting thing is that the response of the first request to www.bet365.com/ looks like this (even with selenium):
Meaning that it does actually reach the server but it just sends a loading screen. Also the following requests get the same response as with the normal browser. Only the requests with status 101 don't give back any response, unlike with the normal browser.
Last interesting thing is this request www.bet365.com/increment?desktop-site-loaded_11=1. It is only made when starting it with the selenium browser, not when opening the site with a normal browser. This might mean that its not a loading problem but that its actively blocking the request and telling the backend to increase a counter of requests that were blocked.
Any ideas how I can get the code working or why this problem comes up?
try
driver.execute_script(f"location.href='{url}';")
instand of
driver.get

Inconsistent execution of executeScript in Cordova inAppBrowser on iOS

I'm having some trouble with some inAppBrowser behavior in my cordova app. Here's the code:
var codePass = fooCode;
var executeScriptFunc = function(event) {
ref.executeScript({
code: codePass
}, function (value) {});
ref.removeEventListener('loadstop', executeScriptFunc);
};
var ref = cordova.InAppBrowser.open(fooObject.link, "_blank", "location=yes,enableViewportScale=yes");
ref.addEventListener('loadstop', executeScriptFunc)
The strange thing here is that the code works perfectly every time when emulated. It opens the browser and executes the script no problem. But when I try it on my actual iPhone device, it doesn't always work. The script executes maybe every other time. But it's never even that consistent.
Both the emulator and iPhone are using iOS 9.3.4. Any ideas?
If the site inside the inAppBrowser happens to be served via HTTPS, the callback for executeScript() will not work if the site employs a Content-Security-Policy HTTP response header that does not contain the gap: or gap-iab: schemes for the default-src directive. These are needed because execution of the callback function on iOS relies on an iframe that gets added to the page.
You can check whether this is the root cause for the problem by opening Safari’s Web Inspector for the inAppBrowser—it has a separate Web Inspector instance, independent of the parent application that opened it—and look out for a corresponding error message in the console. Note that you should open the console before executeScript() is run, or otherwise you might not get the error message.
Make sure also that you don't have other event handlers firing at the same time during your polling.
I had multiple pollers all firing every second and that's when I ran into the issue.
After changing the polling time so they all fired at different times, the issue went away.

Chrome Extension API not firing onChanged event

I am using chrome.downloads.onChanged.addListener to find out when a download completes.
The callback does not fire sometimes, and there is no apparent reason for it.
The code looks like this
chrome.downloads.onChanged.addListener(function (downloadDelta) {...});
and it is in background.js and file is mentioned in background section of manifest. I added console.log(downloadDelta); at the very begining of callback, but it is not fired.
The API is mentioned here
EDIT: Test extension
Most probably this has to do with peculiarities of Event pages - something not working properly when your page gets unloaded.
This is easy to test - remove "persistent": "false" from the manifest.
That said, your test extension does not violate any Event page recommendations and chrome.downloads API does not list any incompatibilities. Therefore, 2 scenarios are possible:
It's quite possible that you are misinterpreting results due to the page being unloaded. For instance, if the page gets unloaded between the callback executing and you opening the devtools for it - the console and all local state will be wiped.
To test for that, make sure to write your diagnostics to persistent storage - chrome.storage API is one option for this.
If you are 100% sure the above is not the case, there may be a bug related to event pages and chrome.downloads. In that case, it should be reported.

how to fix iframe load never terminating the browser visual spinner and 'Transfer ...' status

I have pages loading json into hidden iframes from javascript.
The Firefox browser seems to never acknowledge fully receiving the iframe content, and reports 'Transferring data from ...' on the status line, and shows the twirly 'busy' icon on the tab, indefinitely.
I am using jQuery to bind the 'load' handlers, and would prefer a solution that does not involve over-riding jQuery functionality.
btw, the load handler does fire, the json received is complete, and the iframe itself gets .remove()d in the cleanup code. The browser still waits for something to signal completeness.
Ben Nadel posted a blogpost on just this topic.
It seems that Firefox acknowledges that an iframe document was completely received only after the onload handler returns. If the iframe is deleted from the DOM within the handler, Firefox never detects completion. The solution Mr Nadel suggested, and which I used, is to use the javascript timer to call a deletion function to run after a brief delay. This allows the handler to return while the iframe persists, but does not let the iframe linger around.

Event onBrowserClose for Google Chrome Extension?

I am developing an extension for Google Chrome. My background script, everytime, authorizes on a server that uses the XMPP API, and subscribes for a PubSub node. I need to unsubscribe on the exit, otherwise the dummy subscriptions will remain on the server. Is There any onBrowserClose event in the Google Chrome Extension APIs?
There is no such event in the Chrome Extension API.
There is however a chrome.windows.onRemoved event that fires each time a window closes. I figured you could check in this event if you closed the last window, but unfortunately due to the asynchronous nature of Chrome this doesn't work.
What I tried was running a simple AJAX request in the onRemoved event handler. The AJAX request never got to the server, as Chrome had already closed before running the event (or just disregarded it).
Making the final answer be: No, currently you can't, as far as I know. You might want to star the following bug report at http://crbug.com/30885 to get noticed on updates.
If you catch the case when the number of open tabs is 0, you can treat that as a Chrome onClose event. In my case, I have to cancel a desktop notification before Chrome closes because it was crashing otherwise.
This is how I did it:
1. Initialize a variable num_tabs by using the following:
chrome.tabs.getAllInWindow( null, function( tabs ){
console.log("Initial tab count: " + tabs.length);
num_tabs = tabs.length;
});
2. Increment num_tabs when a tab is created:
chrome.tabs.onCreated.addListener(function(tab){
num_tabs++;
console.log("Tab created event caught. Open tabs #: " + num_tabs);
});
3. Decrement num_tabs when a tab is removed and run your browser onclose event handler if num_tabs = 0
chrome.tabs.onRemoved.addListener(function(tabId){
num_tabs--;
console.log("Tab removed event caught. Open tabs #: " + num_tabs);
if( num_tabs == 0 )
notification.cancel();
});
Adding a browser close event is a pretty frequent request. Star http://crbug.com/30885 for updates. And read the bug report for a clever hack to detect when the browser is shut down via a key press.
This one works for me:
chrome.windows.onRemoved.addListener(function(windowId){
alert("!! Exiting the Browser !!");
});
It takes chrome.windows rather than chrome.tabs.
TL;DR: Try window.onunload event, it works for some cases.
As it was mentioned before we generally can't handle something like onBrowserClose event and prevent browser from closing. But for some cases we can use window.onunload event for doing something synchronously, and it does work if it really synchronously.
From my experience you can at least:
Save some information in (for example logs) in HTML5 localStorage (which is synchronous).
Call some asynchronous chrome extension API functions but you can't get a result. (It works for me! Yay!)
Perform synchronous XMLHTTPRequest (yeah, sometimes it works).

Categories