简体   繁体   中英

Chrome Extension - Trigger not Work

i try create simple Chrome Extension, after click button in pop-up, i need send function setInput() to page, function change value and i need use trigger('keyup'), if i try use this function in Chrome Console - trigger work. But if i send this function after click in pop-up - trigger not work(

Chrome Extension - Trigger not Work

在此处输入图片说明

Console - Trigger Work

在此处输入图片说明

popup.html

<head>
  <script src="popup.js"></script>
</head>
<body>
    <div class="btn">Click</div>
</body>

popup.js

function sendMessage() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
   });
}

function onWindowLoad() {
    chrome.tabs.executeScript(null, { file: "PageReader.js" });
}

document.addEventListener("DOMContentLoaded", function() {
    var btn = document.querySelector('.btn');
    btn.addEventListener('click', function() {

        sendMessage();

    });
});

window.onload = onWindowLoad;

PageReader.js

- in file top i include Jquery

    function setInput() {
        var input = $('.text input');
        input.val('1111').trigger('keyup');
    }

    chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {
            if( request.message === "start" ) {
                setInput();
            }
        }
    );

thanks all for help, i find answer, i delete jQuery, and create event "keyup"

Old:

var input = $('.text input');
input.val('1111').trigger('keyup');

New:

var evt = document.createEvent('KeyboardEvent');
evt.initEvent('keyup', true, true);
var input = document.querySelector('.text input');
input.value = '1111';
input.dispatchEvent(evt);

Please add debugger after btn.addEventListener('click', function() { too see what is going on. if this event handler is attached.

Second thing - you may want to wrap you initialisation code into setTimeout call with let's say 100ms of delay, to check if this page you are dealing with is not only working with some framework that generates this HTML and this is done after DOMContentLoaded . This means basically wrap everything inside

document.addEventListener("DOMContentLoaded", function() {

with setTimeout(function() {/*everything inside goes here*/}, 100)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM