modified innerHTML does not show on page - google-chrome-extension

I am writing a Google extension. Here my content script modifies a page based on a list of keywords requested from background. But the new innerHTML does not show up on the screen. I've kluged it with an alert so I can see the keywords before deciding to actually send a message, but it is not how the routine should work. Here's the code:
// MESSAGE.JS //
//alert("Message Page");
var keyWordList= new Array();
var firstMessage="Hello!";
var contentMessage=document.getElementById("message");
contentMessage.value=firstMessage;
var msgComments=document.getElementsByClassName("comment");
msgComments[1].value="Hello Worlds!";//marker to see what happens
chrome.extension.sendRequest({cmd: "sendKeyWords"}, function(response) {
keyWordList=response.keyWordsFound;
//alert(keyWordList.length+" key words.");//did we get any keywords back?
var keyWords="";
for (var i = 0; i<keyWordList.length; ++i)
{
keyWords=keyWords+" "+keyWordList[i];
}
//alert (keyWords);//let's see what we got
document.getElementsByClassName("comment")[1].firstChild.innerHTML=keyWords;
alert (document.getElementsByClassName("comment")[1].firstChild.innerHTML);// this is a band aid - keyWords does not show up in tab
});
document.onclick= function(event) {
//only one button to click in page
document.onload=self.close();
};
What do I have to do so that the text area that is modified actually appears in the tab?

(Answering my own question) This problem really has two parts. The simplest part is that I was trying to modify a text node by setting its value like this:
msgComments1.value="Hello Worlds!"; //marker to see what happens
To make it work, simply set the innerHTML to a string value like this:
msgComment1.innerHTML="Hello Worlds!"; //now it works.
The second part of the problem is that the asynchronous call to chrome.extension.sendRequest requires a callback to update the innerHTML when the reply is received. I posted a question in this regard earlier and have answered it myself after finding a solution in an previous post by #serg.

Related

Cannot set input field value with Element.value [duplicate]

My extension has a context menu with items. What I'd like it to do: is when I right-click an editable html element (eg input or textarea) and then select and click on an item in my menu - some value defined by my extension gets entered into the input.
For now I have realised that with document.activeElement.value = myValue.
With simple inputs it works alright.
Problems start when there is an input with custom onChange event handling, eg a calendar or a phone input, or currency input - that transforms user-input in some way.
Since I am setting a value directly onto the element - the handling logic gets omitted, which causes all manner of problems.
Since javascript doesn't allow for KeySend-like features - what are my options here?
I have thought about testing tools like Puppeteer or Cypress - but they all seem not to be packageable into an extension. Puppeteer does have such an option, but it still requires a node instance running to connect to. And I would like my extension to be solely client-sided and distributed in Chrome webstore - so I cannot ask my users to spin up a node server.
There is a built-in DOM method document.execCommand.
In case of an extension, use this code in the content script.
// some.selector may be `input` or `[contenteditable]` for richly formatted inputs
const el = document.querySelector('some.selector');
el.focus();
document.execCommand('insertText', false, 'new text');
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
It imitates physical user input into the currently focused DOM element so all the necessary events will be fired (like beforeinput, input) with isTrusted field set to true. On some pages the change event should be additionally dispatched as shown above.
You may want to select the current text to replace it entirely instead of appending:
replaceValue('some.selector', 'new text');
function replaceValue(selector, value) {
const el = document.querySelector(selector);
if (el) {
el.focus();
el.select();
if (!document.execCommand('insertText', false, value)) {
// Fallback for Firefox: just replace the value
el.value = 'new text';
}
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
}
return el;
}
Note that despite execCommand being marked as obsolete in 2020, it'll work in the foreseeable future because a new editing API specification is not finished yet, and knowing how slow such things usually move it may take another 5-20 years.
#wOxxOm, thank you very much !
I used your code solved my problem which has bothered me for long time. I googled many code and article for nearly one month.
It works on Facebook and many strong website.
Because execCommand has depredated, I try below code it works well, include Facebook.
function imitateKeyInput(el, keyChar) {
if (el) {
const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:'', code:'', location:0};
el.dispatchEvent(new KeyboardEvent("keydown", keyboardEventInit));
el.value = keyChar;
el.dispatchEvent(new KeyboardEvent("keyup", keyboardEventInit));
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
} else {
console.log("el is null");
}
}
The following code can only work on ordinary websites, but it is invalid for strong website.
function fireKeyEvent(el, evtType, keyChar) {
el.addEventListener(evtType, function(e) {el.value += e.key;}, false);
el.focus();
const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:keyChar, code:'', location:0};
var evtObj = new KeyboardEvent(evtType, keyboardEventInit);
el.dispatchEvent(evtObj);
}

How to display standby dialog in XPages view when expanding a section

In my XPages application I am using the xe:dynamicViewPanel control and would like to add a standby/wait dialog/popup when a section is being expanded by the user (click on the expand-icon to open the section).
Sometimes the view index is not up-to-date and opening a category holding a lot of documents will last a while, in the meantime I want to display some "loading dialog" (which I already have, so, no need to explain how to do this).
My problem is, that I can not find any event or entry point where to start from.
Thank you all !
Alex
You can try code from this link:
https://openntf.org/XSnippets.nsf/snippet.xsp?id=standby-dialog-custom-control
If you want to show stanby dialog on the current section, replace the 79 line
var forms=dojo.body()
with some other container. For example, a partial refresh element
var forms = dojo.byId(refreshId)
In this case you need to replace lines 75 and 140 to pass the id parameter
function StandbyDialog_Started(refreshId) {
try{
if(StandbyDialog_Do==true){
if(this.StandbyDialog_Obj==null) {
var forms= (refreshId)?dojo.byId(refreshId):dojo.body();
this.StandbyDialog_Obj = new dojox.widget.Standby({
target: forms,
zIndex: 10000
});
document.body.appendChild(this.StandbyDialog_Obj.domNode);
this.StandbyDialog_Obj.startup();
}
StandbyDialog_StoreField()
setTimeout("if(StandbyDialog_Do==true){StandbyDialog_StoreField()}",50);
setTimeout("if(StandbyDialog_Do==true){this.StandbyDialog_Obj.show()}",200);
}
}catch(e){
console.log("StandbyDialog_Started:"+e.toString())
}
}
and
dojo.subscribe( 'partialrefresh-start', null, function( method, form, refreshId ){
StandbyDialog_Do=true
StandbyDialog_Started(refreshId)
});
I didn't test it, but I hope it can help you to go further.

Element is not currently visible and so may not be interacted with node and selenium driver

I have the following code and I cannot get the driver to click the div. It keeps throwing the error
"Element is not currently visible and so may not be interacted"
when debugging you can clearly see that the element is visible. How can I ignore the warning or the error?
var webdriver = require('selenium-webdriver')
, By = webdriver.By
, until = webdriver.until;
var driver = new webdriver.Builder().forBrowser('firefox').build();
driver.get('http://www.vapeworld.com/');
driver.manage().timeouts().implicitlyWait(10, 10000);
var hrefs = driver.findElements(webdriver.By.tagName("a"));
hrefs.then(function (elements) {
elements.forEach(function (element) {
element.getAttribute('name').then(function (obj) {
if (obj == '1_name') {
console.log(obj);
element.click();
}
});
});
});
Your code is clicking an A tag with the name "1_name". I'm looking at the page right now and that element doesn't exist, hidden or otherwise.
You'd be better served by replacing the bulk of your code with a CSS selector, "a[name='1_name']" or "a[name='" + tagName + "']", that will find the element you want with a single find. You can then click on that element.
The issue you are running into is that the element you are trying to click is not visible, thus the error message. Selenium is designed to only interact with elements that the user can see, which would be visible elements. You will need to find the element you are looking for and figure out how to make it visible. It may be clicking another link on the page or scrolling a panel over, etc.
If you don't care about user scenarios and just want to click the element, visible or not, look into .executeScript().
Looked at the website and used the F12 tool (Chrome) to investigate the page:
var elements = [].slice.call(document.getElementsByTagName("a"));
var elementNames = elements.map(function (x) { return x.getAttribute("name"); });
var filledElementNames = elementNames.filter(function (x) { return x != null; });
console.log(filledElementNames);
The content of the website http://www.vapeworld.com is very dynamic. Depending on the situation you get one or more anchors with "x_name" and not always "1_name": the output of the script in Chrome was ["2_name"] and Edge returns ["1_name", "9_name", "10_name", "17_name", "2_name"]. So "you can clearly see that the element is visible" is not true in all situations. Also there were some driver bugs on this subject so it is worthwhile to update the driver if needed. See also the answers in this SO question explaining all the criteria the driver uses. If you want to ignore this error you can catch this exception:
try {
element.click();
} catch (Exception ex) {
console.log("Error!");
}
See this documentation page for more explanation.

Updating an extension button dynamically - inspiration required

I am building an extension where I want to be able to add a signifier to the extension button when the extension in the code has been activated. I was hoping I could add text to the extension button (top right)
Here is a simple scenario. Let's say my extension monitors browsing and gets the tab url, in my extension I have a list of domains to watch for.
Watch for these domains
www.website1.com
www.website2.com
If a user visits a domain in the watched list I want to indicate this somehow, by adding some text somewhere - I was hoping in the top right of the browser where the extensions buttons are. I don't really want to use a notification window as I want something unobtrusive. The text that I want to display would just be a few letters but different for different urls.
Does anyone have any inspiration?
Thanks
You may change the extension icon like this:
chrome.browserAction.setIcon({path: icon});
There is also a 'badge' - small box over the extension icon that shows ie. number of unread messages in gmail extension. You can manipulate it like this:
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:"?"});
It is also possible to generate icon dynamically on a canvas element and then display it like this:
chrome.browserAction.setIcon({imageData:canvasContext.getImageData(0, 0, canvas.width,canvas.height)});
Note that you must call this from your background script, since the content script will not have permission!
tl;dr: Call it from background.js
I googled around this comment because I was trying to call a chrome.browserActions function from my content script
It's only accessible to scripts that are running as part of a chrome extension, since content_scripts are the same as client scripts you'd have to access them through the chrome.* api's
and to fix some addition headaches I had the call for setBadge text needs to look like:
chrome.browserAction.setBadgeText({text: 'ASDF'});
You can put as many characters as you want, but only 4 or so will appear. I got hung up on what the object property needed to be.
You can also set a timeout to check changes on the system every x minutes, and then update de badge.
On my extension, I have an task counter called inside a notification function. Something like :
$.getJSON(
"http://mydomain/notifications?ajax=1&callback=?",
function(data){
var result = data.retorno;
if(result.length > 0){
var totalItens = result[0].total
} else {
var totalItens = 0;
}
chrome.browserAction.setIcon({path: '19.png'});
chrome.browserAction.setBadgeText({text:''+totalItens+''});
for(var i=0; i<result.length; i++){
var imagem = 'http://mydomain/myimage';
var titulo = 'mytitle';
var desciption = 'mydescription';
var urlNot = 'http://mydomain/mypageOnclick';
var not = new Notifier(urlNot);
not.Notify(
imagem, // The image.
titulo, // The title.
desciption // The body.
);
}
}
);
You have to change in 3 files.
manifest.json
Check this code added
"background": { "scripts": ["background.js"], "persistent": false }
script.js
Add the following code:
const msg = 'updateIcon'
chrome.runtime.sendMessage({ message: msg }, function(response) {
});
background.js
Add the following code:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(request);
// Callback for that request
chrome.browserAction.setIcon({path: "/assets/icon.png"});
});

Chrome Extension iframe dom reference disqus

How do I get a reference to the dom of a cross domain iframe/frame?
I want to do some stuff to disqus comments with an extension.
My manifest has the following:
"all_frames": true,
"matches": ["*://*.disqus.com/*","*://disqus.com/*", "http://somesite.com"]
I am not trying to communicate outside of the frame - that is the js will take care of the work without needing to 'tell' me anything.
all_frames should inject the listed js files into every frame, no?
When I do this:
if (window != window.top){
alert('In an IFRAME: ' + window.location.href);
}
...I get the expected disqus URLs.
But when I do this:
var btnCommentBlock = document.getElementsByClassName('dsq-comment-buttons');
alert('btnCommentBlock length: ' + $(btnCommentBlock).length);
...I get 0 for length.
I updated my answer to Javascript to access Disqus comment textbox?
Basically, Disqus changed the selector. They no longer use textarea, they use contenteditable divs.
Something like this should work:
// We just need to check if the IFrame origin is from discus.com
if (location.hostname.indexOf('.disqus.com') != -1) {
// Extract the textarea (there must be exactly one)
var commentBox = document.querySelector('#comment');
if (commentBox) {
// Inject some text!
commentBox.innerText = 'Google Chrome Injected!';
}
}
Source Code:
https://gist.github.com/1034305
Woohoo! I found the answer on github:
https://gist.github.com/471999
The working code is:
$(document).ready(function() {
window.disqus_no_style = true;
$.getScript('http://sitename.disqus.com/embed.js', function() {
var loader = setInterval(function() {
if($('#disqus_thread').html().length) {
clearInterval(loader);
disqusReady();
}
}, 1000);
});
function disqusReady() {
//whatever you can imagine
}
});
I put this in the disqusReady() function:
var aTestHere = document.getElementsByClassName('dsq-comment-body');
alert(aTestHere[0].innerHTML);
...and got back the innerHTML as expected.
Mohamed, I'd really like to thank you for taking the time to interact with my question. If you hadn't posted that link to github there's no telling when if ever I'd have figured it out or found the other code.
edit: After a few minutes of experimenting it looks like it is not necessary to call getScript so you should be able to comment that out.
Also unnecessary is window.disqus_no_style so I commented that out too.
I'll experiment some more and update the answer later. One of those two things prevented me from being able to actually post a comment at the disqus site I use. //them out still allows access to the dom and the ability to post.

Resources