Событие клика не прикрепляется к кнопке на нескольких вкладкахJquery

Программирование на jquery
Ответить Пред. темаСлед. тема
Гость
 Событие клика не прикрепляется к кнопке на нескольких вкладках

Сообщение Гость »

У меня есть расширение Chrome (манифест версии 3), которое добавляет пользовательскую кнопку на несколько различных веб-страниц ServiceTitan, а затем присоединяет к этой кнопке обработчик событий щелчка. Все это прекрасно работает, когда это делается только на одной странице браузера. Но когда я открываю несколько веб-страниц на разных вкладках и кнопка появляется на каждой странице, мое событие щелчка иногда не прикрепляется к кнопке на одной из вкладок/страниц. По-прежнему отлично работает на других вкладках. Так что это несколько спорадично, но вполне воспроизводимо. Когда я перемещаюсь по разным страницам, наблюдаю за своей пользовательской кнопкой и нажимаю ее, очень скоро я обнаруживаю вкладку, на которой событие нажатия не было прикреплено к моей кнопке.
Вот как прикрепить событие клика:

Код: Выделить всё

$("#btnEZsaltGo").on("click", function(){ezsaltButtonClicked()});
Опять же, в большинстве случаев это работает отлично, но при использовании нескольких вкладок иногда это не работает. Но кнопка появляется всегда, во всех случаях.
Примечание: я использую не фоновый сценарий, а только сценарий содержимого.
Как я могу привязать событие клика к моей пользовательской кнопке на каждой вкладке во всех случаях?
Вот полный исходный код:

Код: Выделить всё

var interval = 0;
var rootEZsaltURL;

console.log("EZsaltGo extension loaded...");

if(location.href.indexOf("next.servicetitan.com") > -1 || location.href.indexOf("integration.servicetitan.com") > -1){ // Sandbox ServiceTitan
rootEZsaltURL = "https://test.ezsaltgo.com/ServiceTitanLanding.php?CustomerID="; // TEST EzsaltGo
}else if(location.href.indexOf("go.servicetitan.com") > -1){ // LIVE ServiceTitan
rootEZsaltURL = "https://ezsaltgo.com/ServiceTitanLanding.php?CustomerID="; // LIVE EZsaltGo
}

(function() { // initial page load (static page content)
interval = setInterval(function(){ checkForEZsaltButton(); }, 1000);
})();

function checkForEZsaltButton() {
if($("#btnEZsaltGo").length == 0){ // only create the ezsalt button if it's not already there
var insertBeforeAnchorElement; // insert the EZsaltGo button BEFORE this element
var insertAfterAnchorElement; // insert the EZsaltGo button AFTER this element
var pageType;
var buttonMarginLeft = 0;
var buttonMarginRight = 0;
var hasBillingAddress = ($("span:contains('Billing Address')").length > 0);
var hasServiceAddress = ($("span:contains('Service Address')").length > 0);
var hasMoreActionsMenu = ($('div[data-testid="more-actions-menu"]').length > 0);
var hasCustomerIDSpan = ($("span:contains('Customer ID')").length > 0);
var hasCustomerIDLink = ($('a[role="link"][href*="/Customer/"]').length > 0);
var isModal = ($("h2.Modal__header-title").length > 0);

if((hasBillingAddress || hasServiceAddress) && hasMoreActionsMenu && (hasCustomerIDSpan || (!hasCustomerIDSpan && hasCustomerIDLink))){
// clearInterval(interval);
// console.log("Customer DIV loaded!! Interval stopped.");

if(isModal){
// we're inside the modal customer window
pageType = "modal";
insertAfterAnchorElement = $("h2.Modal__header-title"); //
}else{
// we're inside a normal ST web page - let's figure out which page exactly

if(location.href.indexOf("/customer/") > 0) pageType = "customer";
if(location.href.indexOf("/location/") > 0) pageType = "location";

if(pageType == "customer"){
insertBeforeAnchorElement = $("div.ButtonGroup").parent();
// no margin padding needed
}

if(pageType == "location"){
insertBeforeAnchorElement = $("div.ButtonGroup").parent().parent();
buttonMarginRight = 19;
}
}

var ezsaltButton = $('EZsaltGo');

if(insertBeforeAnchorElement){
ezsaltButton.insertBefore(insertBeforeAnchorElement);
}else if(insertAfterAnchorElement){
ezsaltButton.insertAfter(insertAfterAnchorElement);
}else{
return; // we don't have anything to anchor against, so just return
}

$("#btnEZsaltGo").on("click", function(){ezsaltButtonClicked()});

// attach click event to the little X at the top right of the modal - if that is clicked, the modal will close, and we need to resume checking
if($(".Modal__header-close").length > 0){
$(".Modal__header-close").on("click", function(){
//interval = setInterval(function(){ checkForEZsaltButton();  }, 1000);
console.log("Modal closed. Interval check resuming...");
});
}
}
}else{
// check whether click event handler has been attached - doesn't work

// var clickHandlers = $("#btnEZsaltGo").data('events')?.click; // clickHandlers always null even when button is there and click handler is attached
// if(clickHandlers && clickHandlers.length > 0) doSomething(); //  clickHandlers always null even when button is there and click handler is attached
}
}

function ezsaltButtonClicked(){
console.log("EZsalt button clicked!");

if(rootEZsaltURL && rootEZsaltURL != ""){
var customerID = getCustomerIDForEZsalt();

if(customerID && customerID != ""){
window.open(rootEZsaltURL + customerID);
}else{
alert("Unable to locate Customer ID. Contact EZsalt.");
}
}else{
alert("EZsalt URL could not be obtained. Contact EZsalt.");
}
}

function getCustomerIDForEZsalt(){
var hasCustomerIDSpan = ($("span:contains('Customer ID')").length > 0);

if(hasCustomerIDSpan){
var customerIDSpan = $("span:contains('Customer ID')");
var customerIDChunk = customerIDSpan.next('p');
return $.trim(customerIDChunk.html());
}else{
var hasCustomerIDLink = ($('a[role="link"][href*="/Customer/"]').length > 0);

if(hasCustomerIDLink){
var hrefChunk = $('a[role="link"][href*="/Customer/"]').attr('href');
var customerID = $.trim(hrefChunk.match(/\d+/)[0]);
return customerID;
}
}

return ""; // something went wrong - should never get this far
}
Я экспериментировал с этой функцией как с возможным способом ее решения:

Код: Выделить всё

function isClickHandlerAttachedToButton(){
// check whether click event handler has been attached
var clickHandlers = $("#btnEZsaltGo").data('events')?.click;
var clickHandlerIsAttached = (clickHandlers && clickHandlers.length > 0);
return clickHandlerIsAttached;
}
Но в 100 % случаев он возвращает значение null, даже если событие щелчка явно привязано к кнопке, потому что я могу нажать на нее, и это работает (запускается новая страница).

Подробнее здесь: https://stackoverflow.com/questions/781 ... tiple-tabs
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Событие клика JQuery не работает после первого клика
    Anonymous » » в форуме Jquery
    0 Ответы
    32 Просмотры
    Последнее сообщение Anonymous
  • Определить событие клика из общего элемента HTML
    Гость » » в форуме Jquery
    0 Ответы
    29 Просмотры
    Последнее сообщение Гость
  • Как добавить событие клика в UIImageView внутри UITableviewCell?
    Anonymous » » в форуме IOS
    0 Ответы
    43 Просмотры
    Последнее сообщение Anonymous
  • Обнаруживать событие клика только на псевдоэлементе
    Anonymous » » в форуме Jquery
    0 Ответы
    35 Просмотры
    Последнее сообщение Anonymous
  • Обнаруживать событие клика только на псевдоэлементе
    Anonymous » » в форуме CSS
    0 Ответы
    27 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Jquery»