This may be a really simple problem but I can't seem to find why this is happening. I'm trying to develop a SPA in vanilla js using webpack, so far I was able to implement routing
with hashchange event and triggering rerendering. But when I tried to add an active class to the relevant link though when the hash changes, It doesn't work. But when I log to the console, it seems that class was added successfully, but in the HTML it doesn't get updated. Why is this?
this is my hashchange listener,
window.addEventListener("hashchange", (e) => {
const hash = window.location.hash.replace("#", "");
const view = routes.find((route) => {
return route.path == hash;
});
const links = document.querySelectorAll(".nav-list--link");
app.render(view.name);
links.forEach((l) => {
const hashHref = l.getAttribute("href").replace("/#", "");
if (hash === hashHref) {
l.classList.add("active");
console.log(l, l.classList);
} else {
l.classList.remove("active");
console.log(l, l.classList);
}
});
});
And this is the console output,
This is the HTML,
I don't understand why it doesn't update in the HTML if it's shown as updated in Javascript
I'm currently setting scrollPositionRestoration: 'enabled' and implementing RouteReuseStrategy that only kicks in when users navigate via next/back button. In safari, scrollPositionRestoration returns to where i was every time. In chrome, some of the time it works, but most of the time it doesn't. I don't really know what's wrong so i'm not posting any codes.
Until I find another way to solve this problem, this is the only solution I found:
-Just add this code to your app-routing.module.ts file,
constructor(router: Router, viewportScroller: ViewportScroller) {
router.events
.pipe(filter((e): e is Scroll => e instanceof Scroll))
.subscribe((e) => {
if (e.position) {
// backward navigation
setTimeout(() => {
viewportScroller.scrollToPosition(e.position);
}, 0);
} else if (e.anchor) {
// anchor navigation
console.log(e.anchor);
viewportScroller.scrollToAnchor(e.anchor);
} else {
// forward navigation
viewportScroller.scrollToPosition([0, 0]);
}
});
}
How to get the 'clipboard' content in cypress. I have a button in my web application, on click of button system will perform 'copy to clipboard' and a message will get displayed. Below is an example of the url content that is copy to clipboard ( this url content is different from web site url)
https://someurl.net/machines/0c459829-a5b1-4d4b-b3c3-18b03c1c969a/attachments/a30ceca7-198e-4d87-a550-04c97fbb9231/download
I have double check that there is no href attribute in that button tag. So I have use a plugin called clipboardy and I have added plugins/index.js file
const clipboardy = require('clipboardy');
module.exports = ( on ) => {
on('task', {
getClipboard () {
return clipboardy.readSync();
}
});
};
In my test I have used cy.task() to get the clipboard content, but this is not printing the actual url content
cy.get('td').find('div').find('span').find('button').find('i').eq(0).click().then(()=>{
cy.task('getClipboard').then((data)=>{
console.log("Helloooo:"+data);
})
})
<td class="sc-hgRTRy duUdhJ">
<div>
<span class="sc-bYwvMP jTmLTC">
<span class="sc-jzJRlG iVpVVy">
<span role="button" aria-expanded="true" aria-haspopup="true" aria-owns="5aa03785-1370-455e-a838-4154f7481a7b">
<button class="sc-feJyhm cJOKrG">
<i class="icon fas fa-link sc-htpNat cQABgO" aria-hidden="true" data-component-type="icon">
</i>
</button>
</span>
</span>
</span>
</div>
</td>
If you don't want to use clipboardy package you can also use this:
cy.window().then((win) => {
win.navigator.clipboard.readText().then((text) => {
expect(text).to.eq('your copied text');
});
});
in your case, it turns to something like
cy.get('td').find('div').find('span').find('button').find('i').eq(0).click().then(()=>{
cy.window().then((win) => {
win.navigator.clipboard.readText().then((text) => {
console.log("Helloooo:"+text);
});
});
})
Accessing clipboard can be worked around, but the main issue is that the document.execCommand('copy') doesn't work (as stated above), which I reckon is the primary (and only?) way for your app to programmatically put a text to user's clipboard.
Assuming it happens somehow (or is fixed upstream), the checking the clipboard's contents can be done e.g. by using clipboardy:
npm i -D clipboardy
plugins/index.js:
const clipboardy = require('clipboardy');
module.exports = ( on ) => {
on('task', {
getClipboard () {
return clipboardy.readSync();
}
});
};
In your specification:
describe('test', () => {
it('test', () => {
cy.document().then( doc => {
doc.body.innerHTML = '<input id="inp">';
});
cy.get('#inp').type('test{selectall}');
cy.document().then( doc => {
doc.execCommand('copy');
});
cy.task('getClipboard').should('contain', 'test');
});
});
I hope this code will be usefull for you.
Thank you.
I have found this nice and simple solution of testing the clipboard content in Gleb Bahmutov's video Access the clipboard from Cypress test using Electron browser.
cy.window().its('navigator.clipboard')
.invoke('readText').should('equal', 'copied text')
It uses the new Clipboard API (Chrome, FF and Opera: 2018; Safari and Edge: 2020; IE: no)
In the video, Gleb also suggets to test a case for browsers not supporting the Clipboard API, using an old (and deprecated) method of document.execCommand('copy').
It expects the page to have an input field or textarea to paste the content. Let's assume it's textarea#paste-here.
// delete navigator.clipboard to force the app to use execCommand
cy.visit('index.html', {
onBeforeLoad(window) {
delete window.navigator.__proto__.clipboard
}
})
cy.document().then(document => cy.spy(document, 'execCommand').as('exec'))
/* trigger the copy action here... cy.get(...).click() */
cy.get('#exec').should('have.been.calledOnceWith', 'copy')
cy.get('#paste-here').focus()
cy.document().invoke('execCommand', 'paste')
cy.get('#paste-here').should('have.value', 'copied text')
Due to the clipboard permissions dialog, this test can be automated (CI) only in Electron browser. To make it running in Chrome, take a look at another Gleb's video Give Chrome Browser Clipboard Permissions from Cypress Test. Otherwise, you can limit the test to be run only in Electron using Test configuration object:
describe('Clipboard', {browser: 'electron'}, () => {
...
Late but if anyone is getting "Document is not focused" error from #marzzy's answer:
cy.window().then((win) => {
win.navigator.clipboard.readText().then((text) => {
expect(text).to.eq('your copied text');
});
});
It's either because:
You are executing code from the devtools console or snippets
Or if you're using Chrome you have to give it clipboard permission like this:
cy.wrap(
Cypress.automation('remote:debugger:protocol', {
command: 'Browser.grantPermissions',
params: {
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
origin: window.location.origin,
},
}),
);
Source: https://www.youtube.com/watch?v=4eEc3x24D64
I managed to get the copied link by printing out the yielded value after clicking the button and then searched the object in the console in order to find the link. I found the link in [object]._vClipboard.clipboardAction.text, as you can see below:
cy.get('[data-test=copy-link-button]').click().then(($clipboard) => {
const copiedLink = $clipboard[0]._vClipboard.clipboardAction.text;
cy.visit(copiedLink);
});
I hope that this will help.
Reading this really helped me solve my own issue, I had to use a mixture from the OP and the first comment. This is what worked for me:
cy.get(':nth-child(2) > .mat-card > .row > .col-sm-3 > .mat-focus-indicator').click().then(() => {
cy.task('getClipboard').then(($clip) => {
const url = $clip;
cy.log('this is what was in clipboard', url);
cy.visit(url);
});
});
This gave me the URL i wanted from the button I clicked. I then just passed that right into cy.visit to visit the url i just copied. Worked great.
For me, none of the answers helped me taking de data from the clipboard. The next code worked:
First we will allow the access to the clipboard:
cy.window().its('navigator.permissions')
.invoke('query', { name: 'clipboard-read' })
.its('state').then(cy.log)
Then we access the clipboard
cy.window().its('navigator.clipboard')
.invoke('readText')
.then((text) => {
cy.log(text)
})
Hope this works for anyone here
Code at https://stackoverflow.com/a/61653634/2742007 should be adapted to call clipboardy functions supported by browsers, as commented by "opike": mind the async and read() instead of readSync().
const clipboardy = require('clipboardy');
module.exports = (on, config) => {
on('task', {
async getClipboard() {
return clipboardy.read();
}
});
}
Note: Above usage of window.navigator https://stackoverflow.com/a/68871590/5667941 , only works for Electron. For Chrome user permisson would be required
Try using cy.window() and you can use the navigator.clipboard as normal for pasting and copying.
it("Paste cliboard numbers", () => {
cy.window()
.then((win) => {
return win.navigator.clipboard.writeText("234");
`})`
.then(() => {
cy.get("[data-test=paste]").click();
cy.get("[data-test=calc-input]").should("have.text", 234);
});
});
None of the other answares worked for me so far with the cypress ui but I managedto find a solution without any additional libs or plugins by using the Cypress.Promises and the window.navigator directly ... and here it is:
cy.window().then(win =>
new Cypress.Promise((resolve, reject) =>
win.navigator
.clipboard
.readText()
.then(resolve)
.catch(reject))
).should('eq', '`myExpectedClipboardValue')
You have to give clipboard read permission.Befor click button to have copied text add this.
cy.wrap(Cypress.automation("remote:debugger:protocol", {
command: "Browser.grantPermissions",
params: {
permissions: ["clipboardReadWrite", "clipboardSanitizedWrite"],
// make the permission tighter by allowing the current origin only
origin: window.location.origin
}
}));
I am using twilio API to implement screen sharing in an emberjs app, I am successfully able to share the screen and also toggle on stopping it. Here is my code ->
this.get('detectRtc').isChromeExtensionAvailable(available => {
if (available) {
const { twilioParticipant } = this.get('participant')
if (this.get('stream') && this.get('stream').active) {
this.get('streamTrack').stop()
this.get('userMedia.mediaStream')
.removeTrack(this.get('streamTrack'))
this.set('isEnabled', false)
twilioParticipant.removeTrack(this.get('streamTrack'))
} else {
this.get('detectRtc').getSourceId(sourceId => {
// "cancel" button is clicked
if (sourceId !== 'PermissionDeniedError') {
// "share" button is clicked extension returns sourceId
this.get('userMedia')
.getScreen(sourceId)
.then(mediaStream => {
this.set('isEnabled', true)
this.set('stream', mediaStream)
this.set('streamTrack', mediaStream.getVideoTracks()[0])
twilioParticipant.addTrack(mediaStream.getVideoTracks()[0])
})
.catch(() => { /* do nothing, but return something */ })
}
})
}
} else {
this.get('flash').status(
'base',
this.get('intl').t('chromeExtension.install'),
{
icon: 'alert-circle',
push: true
}
)
// TODO Show the system popup to install chrome extension from web store
// !!chrome.webstore &&
// !!chrome.webstore.install &&
// chrome.webstore.install(this.webStoreUrl)
}
})
The issue I'm facing is with the stop sharing button which is at the bottom of the app as seen in screenshot below
I need a way to listen to an event handler and execute the some code after clicking on the stop sharing screen button, I know there is an onended event Handler which is mentioned in the MediaStreamTrack docs, but I don't know how to use it, any help will be highly appreciated.
https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack
The "stop sharing" button will trigger the MediaStreamTracks 'ended' event. Try this:
mediaStream.getVideoTracks()[0].addEventListener('ended', () => console.log('screensharing has ended'))
for some reason, #philipp answer is not working for me and I found this quite helpful
https://github.com/webrtc/samples/blob/gh-pages/src/content/getusermedia/getdisplaymedia/js/main.js#L88
this.get('stream').addEventListener('inactive', e => {
console.log('Capture stream inactive - stop recording!');
});
I have a google sign-in button on my page, using gapi.signin2.render to render the button (https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid-options).
However it ALWAYS renders as signed-in, despite calling GoogleAuth.signOut(). In fact I can actually call GoogleAuth.signOut() and immediatly check GoogleAuth.isSignedIn.get() to check the state and returns as true.
Does anyone know how to fix this? My sign-out code is as follows:
var GoogleAuth = gapi.auth2.getAuthInstance();
GoogleAuth.signOut().then(() => {
var status = GoogleAuth.isSignedIn.get(); //ALWAYS TRUE!!!!
alert('IP.common.oAuth.signOut: signin status: ' + status);
});
This should be work fine. Delete then(this.props.onLogoutSuccess)) if you don't need it.
signOut() {
if (window.gapi) {
const auth2 = window.gapi.auth2.getAuthInstance()
if (auth2 != null) {
auth2.signOut().then(auth2.disconnect().then(this.props.onLogoutSuccess))
}
}
}
Very nice lib, if you wanna learn how to work with Google API https://github.com/anthonyjgrove/react-google-login. Yes it's react, but methods should be similar, I think.