execute script only one time until next refresh - javascript

I am building a chrome extension and i am executing a action on the extension icon
chrome.browserAction.onClicked.addListener(function(tab) {
triggerTab(tab);
});
var alreadyClicked = false,ct='';
function triggerTab(tab) {
if (!alreadyClicked || ct != tab.url) {
addMachine(tab);
}
ct = tab.url;
alreadyClicked = true;
}
By this code its only execute script once forever on current tab..
I want to run script only once on a tab until next refresh .

how about adding an eventlistener to onUpdated event?
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
alreadyClicked = false;
});

Related

Firefox - website takes me to new tab automatically and I cannot stop it

So I have a website where I can select links and click a button to open them all at the same time. When I do that Firefox takes me to one of the newly opened links automatically.
I wanted to stop this behavior, so I looked and looked, and eventually found this option:
browser.tabs.loadDivertedInBackground
Now, when I set this to true, newly opened tabs never automatically take me to them. So if I click an ad on a site that normally opens in a new tab and takes me to it, now it doesn't happen. I also tried this code:
<p><a href="#" onclick="window.open('http://google.com');
window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
This code opens 2 links at the same time. I was thinking maybe opening multiple links at the same time somehow overrides Firefox. But no, the links opened and I was not automatically taken to any of the new tabs.
Also must be said that I'm having this problem in Firefox 75 and 74. But when I try it in Firefox 55.0.2, I don't have the problem. In Firefox 55.0.2 the "browser.tabs.loadDivertedInBackground" actually works even on the website where I have the problem (I can't share the site because it's behind login).
This appears to be the code responsible to open multiple links on the website I have an issue with:
$(document).on('click', '.statbtn', function () {
var me = $(this);
var isAnyRowSelected = false;
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
$('select[name="status[' + t.val() + ']"]').val(me.attr('id'));
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
$(document).on('click', '.openlink', function () {
var me = $(this);
var isAnyRowSelected = false;
$($('.row-checkbox').get()).each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
console.log();
var win = window.open(t.data('link'), '_blank');
if (win) {
win.focus();
} else {
bootbox.alert('Please allow popups for this website');
}
}
});
So I tried everything I could think of. Many changes to the about:config, restarting my browser, unticking the "When you open a link in a new tab, switch to it immediately" option in Firefox. But nothing works. When I open links from this one site using this specific button, I always get automatically taken to one of the newly opened tabs.
Here is a similar-ish problem - https://www.reddit.com/r/firefox/comments/bnu6qq/opening_new_tab_problem/
Any ideas why this happens and how to fix it? I mean, a website shouldn't be able or allowed to override Firefoxe's native setting, right?
Okay, because I don't wanna be an ass, here is the solution.
$(document).on('click', '.statbtn', function () {
var me = $(this);
var isAnyRowSelected = false;
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
$('select[name="status[' + t.val() + ']"]').val(me.attr('id'));
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
$(document).on('click', '.openlink', function () {
var me = $(this);
var isAnyRowSelected = false;
$($('.row-checkbox').get().reverse()).each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
console.log();
// var win = window.open(t.data('link'), '_blank');
setTimeout(() => window.open(t.data('link'), '_blank'),1000);
// if (win) {
// win.focus();
// } else {
// bootbox.alert('Please allow popups for this website');
// }
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
Basically, adding a "setTimeout" fixed it. For some reason Firefox needed the delay to process things correctly, I guess, I think. Before the delay, the actions would happen instantly, and I'll just guess that Firefox couldn't "catch up" to it in order to apply the exemption of not navigating to new tabs. But a timeout delay fixed it.
And for anyone that may run into this with a similar issue, it also required an edit in Firefox in "about:config" to set this to True.
browser.tabs.loadDivertedInBackground
That's all folks :)

How to alter/remove this inline javascript with Greasemonkey?

I found this script in the head of a website:
<script type="text/javascript" >
function Ext_Detect_NotInstalled(ExtName,ExtID) {
}
function Ext_Detect_Installed(ExtName,ExtID) {
alert("We have found unwanted extension. Please contact support")
window.location = "logout.php"
}
var Ext_Detect = function(ExtName,ExtID) {
var s = document.createElement('script');
s.onload = function(){Ext_Detect_Installed(ExtName,ExtID);};
s.onerror = function(){Ext_Detect_NotInstalled(ExtName,ExtID);};
s.src = 'chrome-extension://' + ExtID + '/captured.js';
document.body.appendChild(s);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
function displayErrorAndLogout() {
alert("Please use chrome browser to view the content");
window.location = "logout.php"
}
if (is_chrome==true)
{
window.onload = function() { Ext_Detect('Chrome','ngpampappnmepgilojfohadhhmbhlaek');};
} else {
is_chrome = navigator.userAgent.toLowerCase().indexOf('crios') > -1;
if (is_chrome == false){
if (detectIE()){
displayErrorAndLogout()
}
if (navigator.userAgent.indexOf('UCBrowser') > -1) {
displayErrorAndLogout()
}
This script check internet download manager extension and popup a logout message.
Is this possible to remove or alter this inline java script using Greasemonkey?
If you want to disable the check for the Chrome addon, it's easy: the script assigns a function to onload, so if you simply assign something else to onload, Ext_Detect will never run, and your extension will not be detected:
window.onload = () => null;
Unfortunately, the other part that checks for crios and UCBrowser and runs detectIE runs synchronously, presumably at the beginning of page load, and userscripts cannot reliably run at the very beginning of page load, so that behavior may not be possible to alter, though you could try it with #run-at document-start: displayErrorAndLogout calls alert before assigning to window.location, so if you make it so that alert throws an error, the location will not change:
#run-at document-start
// ==/UserScript==
window.alert = function() {
throw new Error();
};

Capture the browser window (only) close event

var inFormOrLink;
$('a').on('click', function () { inFormOrLink = true; });
$('form').on('submit', function () { inFormOrLink = true; });
$(window).on('beforeunload', function (eventObject) {
var returnValue = undefined;
if (!inFormOrLink) {
returnValue = "Do you really want to close?";
}
if (returnValue != undefined) {
eventObject.returnValue = returnValue;
return returnValue;
}
});
Ref : Browser close event
I tried to execute the above mentioned code in Chrome Version 65.0.3325.181
it is working properly i.e popup does not open while redirecting or submitting form,
i want to show popup only when user close the tab, sometimes browser shows the popup but sometimes tab gets closed without showing popup.
I don't know why it is happening.

Opening links in a new tab with javascript stops working

I have some code on my tumblr blog that makes it so the links in the "notes" div open in a new tab — it works fine but once i click "Show More Notes" (which loads more links), it stops working on those links. Here is my code.
<script type="text/javascript">
$(function(){
$("#notes a").attr("target","_blank");
});
</script>
Here is what tumblr says on this issue: "Notes are paginated with AJAX. If your theme needs to manipulate the Notes markup or DOM nodes, you can add a Javascript callback that fires when a new page of Notes is loaded or inserted"
tumblrNotesLoaded(notes_html) "If this Javascript function is defined, it will be triggered when a new page of Notes is loaded and ready to be inserted. If this function returns false, it will block the Notes from being inserted."
tumblrNotesInserted() "If this Javascript function is defined, it will be triggered after a new page of Notes has been inserted into the DOM."
the newly loaded links wont have target set to _blank ... what you should do, when you've loaded the new links is execute
$("#notes a").attr("target","_blank");
again - as you've shown no code regarding the loading of these links, that's the best I can do
edit: I just looked at your page - I think this should do the trick
this.style.display = 'none';
document.getElementById('notes_loading_121152690941').style.display = 'block';
if (window.ActiveXObject) var tumblrReq = new ActiveXObject('Microsoft.XMLHTTP');
else if (window.XMLHttpRequest) var tumblrReq = new XMLHttpRequest();
else return false;
tumblrReq.onreadystatechange = function() {
if (tumblrReq.readyState == 4) {
var notes_html = tumblrReq.responseText.split('<!-- START ' + 'NOTES -->')[1].split('<!-- END ' + 'NOTES -->')[0];
if (window.tumblrNotesLoaded)
if (tumblrNotesLoaded(notes_html) == false) return;
var more_notes_link = document.getElementById('more_notes_121152690941');
var notes = more_notes_link.parentNode;
notes.removeChild(more_notes_link);
notes.innerHTML += notes_html;
if (window.tumblrNotesInserted) tumblrNotesInserted(notes_html);
// ************************************************
$("#notes a").attr("target","_blank");
// ************************************************
}
};
tumblrReq.open('GET', '/notes/121152690941/lhtXynZtK?from_c=1433902641', true);
tumblrReq.send();
return false;
the added line is surrounded by // ************************************************
You could set target attribute on mousedown delegated event, e.g:
$(function () {
$('#notes').on('mousedown', 'a:not([target])', function () {
this.target = "_blank";
});
});
Use this:
$('ol.notes').on('click', 'a', function (e) {
if (e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.isDefaultPrevented()) {
return;
}
window.open(this.href);
e.preventDefault();
});
This attaches an event handler on the notes container, making sure that it only gets clicks on a elements and that the clicks are not middle-clicks, alt-clicks, …
Once all of those superfluous clicks are filtered out, it simply opens a new tab via Javascript; there's no need to set target="_blank"

Calling Javascript function on browser close

I have a site, now what I want is when user switch to some external site, then an Ad should be popped up, and also when user close the browser window, the Ad should get popup, I have used onunload, but it shows the message on clicking every link, and also I used on beforeunload, it does almost everything, but it do the same as onunload...
Please anyone have some idea how should I achieve this?
This doesn't prevent popup appearing on page refresh, but does this job as requested:
<script>
var isLinkClicked = false;
// Either plain JS solution:
var links = document.getElementsByTagName('a');
var l=links.length;
while (l--) {
links[l].addEventListener("click", function() {
isLinkClicked = true;
}, false);
}
// Or jQuery solution:
$("a").live("click", function() {
isLinkClicked = true;
});
// And then Unload event listener:
window.addEventListener("unload", function(evt) {
if (isLinkClicked) {
isLinkClicked = false;
return false;
}
// here comes the rest of the code
}, false);
</script>

Categories

Resources