如何触发单击按钮

时间:2017-04-08 07:00:56

标签: google-chrome-extension firefox-webextensions

this page。我需要使用AngularJS触发点击此页面上的“立即购买”按钮。

我已经尝试过这些方法点击内容脚本(myscript.js)中的“立即购买”,但不起作用:

if ( tinyMCE.editors['id-of-your-editor'] ) {
    tinyMCE.editors['id-of-your-editor'].save();
    tinyMCE.editors['id-of-your-editor'].load();
    var your_content = tinyMCE.editors['id-of-your-editor'].getContent();
} else if ( document.getElementById( 'id-of-your-editor' ) ) {
    var your_content = document.getElementById( 'id-of-your-editor' ).value;
} else {
    alert ( 'Error' );
}

manifest.json看起来像这样:

   angular.element($('ul form button:contains("BUY NOW")').get(0)).triggerHandler('click');

       $('ul form button:contains("BUY NOW")').get(0).click();

        $('ul form button:contains("BUY NOW")').get(0).dispatchEvent(new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': true
        }));

让它运作的方法是什么?

2 个答案:

答案 0 :(得分:4)

尝试使用此代码;它通过在按钮中心触发的快速连续的mousedown,mouseup和click事件模拟鼠标左键单击元素:

var simulateMouseEvent = function(element, eventName, coordX, coordY) {
  element.dispatchEvent(new MouseEvent(eventName, {
    view: window,
    bubbles: true,
    cancelable: true,
    clientX: coordX,
    clientY: coordY,
    button: 0
  }));
};

var theButton = document.querySelector('ul form button');

var box = theButton.getBoundingClientRect(),
        coordX = box.left + (box.right - box.left) / 2,
        coordY = box.top + (box.bottom - box.top) / 2;

simulateMouseEvent (theButton, "mousedown", coordX, coordY);
simulateMouseEvent (theButton, "mouseup", coordX, coordY);
simulateMouseEvent (theButton, "click", coordX, coordY);

答案 1 :(得分:0)

Vanilla JS怎么样,没有人禁止?

例如“onlick / click”?

function ae(a,b,c) {
 if (a.addEventListener)
     a.addEventListener (b,c,false);
 else if (a.attachEvent)
     a.attachEvent ('on'+b,c); 
}
function re(a,b,c) {
 if (a.removeEventListener) 
    a.removeEventListener (b,c,false);
 if (a.detachEvent)
    a.detachEvent ('on'+b,c); 
}